Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decltype(function) as class member

I have:

int foo(int x) { return x+1; }

struct Bar {
  decltype(foo) operator();
};

int main() {
  Bar bar;
  printf("%d\n",bar(6));
}

which results in the slightly startling compiler error message (g++ 4.6.1):

error: declaration of 'operator()' as non-function

When changing the member name to

  decltype(foo) blubb;

and using it results in a linker error:

undefined reference to `Bar::blubb(int)'

Is this expected behaviour?

like image 377
smilingthax Avatar asked Feb 17 '12 10:02

smilingthax


1 Answers

It seems that you want to "copy" the signature of another function to create a function with the same signature. Since decltype(foo) is indeed the type of the function (and not a pointer to that function, which would be decltype(&foo) and would lead to a pointer declaration), you can use it to declare a function with the same signature as another function.

As indicated by the linker error:

undefined reference to `Bar::blubb(int)'

this will already work fine with your compiler. However it seems that gcc did not yet fully implement this part of the standard, as it will not accept the syntax for the same thing with a function call operator. Clang btw. will happily accept it and the link then errors out with

undefined reference to `Bar::operator()(int)'

Your question about why that linker error exists indicates a misunderstanding of what decltype really does.

It will just evaluate to a type, not more. The definition of blubb is in no way tied to the definition of foo. This might be clearer when writing it like

typedef decltype(foo) x; 
x blubb;

You can now alternatively typedef x to be explicitly the function type, which will not in any way change what blubb is. You still need to define it. And since there is no syntax to define it using decltype, you explicitly have to write it as

int Bar::operator()(int) {
...
}

which will likely and unfortunately defeat the purpose/benefit of using decltype for the declaration, as it will not allow you to automatically "copy" a signature.

like image 165
PlasmaHH Avatar answered Oct 20 '22 18:10

PlasmaHH