Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using decltype to declare the entire function type itself (not pointer!)

So I have a function with a specific signature in a header file, and I want to declare another function with the exact same signature inside a class without typing the parameters again, and of course, hopefully without a macro... The member function should also have an extra hidden parameter obviously, the this pointer (since it's not a static member function).

Now, I'm actually surprised that the following hack/trick works in both GCC and ICC, but I'm not sure if it's "legal" C++. I'm not particularly concerned with legality if it's a supported extension, but unfortunately I do not want it to break on a compiler version update because some people decided to arbitrarily block this useful feature since the standard says "no" (that kind of stuff really annoys me to be honest).

Here's what I mean:

// test.hpp
int func(int x) { return x; }

struct foo
{
  decltype(func) fn;  // <-- legal?
};

int test()
{
  return foo().fn(6);
}


// then in test.cpp
int foo::fn(int x) { return x + 42; }

This works (with GCC and ICC), but I don't know if it's "legal" in the standard. I'm asking just to be assured that it is legal and it won't suddenly stop working in the future.

(if it's not legal and you want to report it as a bug, please mark it as a suggestion to make it a legal compiler extension instead of killing it...)

Basically, it's the same as declaring int fn(int x); in the struct, and that's how it works currently.

If you ask me for a use case: it's to declare a wrapper member function for the other free function which does something with the this pointer before passing it to the free function. Its parameters must match exactly, obviously. Again, I don't want to type the parameters again.

like image 709
kktsuri Avatar asked Jun 03 '17 18:06

kktsuri


People also ask

What does decltype do in C++?

The decltype type specifier yields the type of a specified expression. The decltype type specifier, together with the auto keyword, is useful primarily to developers who write template libraries. Use auto and decltype to declare a function template whose return type depends on the types of its template arguments.

What is the difference between auto and decltype in C++?

auto is a keyword in C++11 and later that is used for automatic type deduction. The decltype type specifier yields the type of a specified expression. Unlike auto that deduces types based on values being assigned to the variable, decltype deduces the type from an expression passed to it.

Is decltype runtime or compile time?

decltype is a compile time evaluation (like sizeof ), and so can only use the static type.


1 Answers

That looks legal; but at definition you have to retype. Consider using perfect forwarding instead.

like image 169
Yakk - Adam Nevraumont Avatar answered Oct 04 '22 02:10

Yakk - Adam Nevraumont