I was playing with decltype and found strange thing. Why do I have this error when trying to decltype a free function? It works well with lambdas, but not with a free function. What do I do wrong here?
#include <iostream>
using namespace std;
int fun()
{
cout << "inside fun" << endl;
return 1;
}
int main()
{
decltype(fun()) x = 2;
cout << x << endl;
auto lambda = [] () -> int { cout << "inside lambda" << endl; return 3; };
decltype(lambda) l = lambda;
l();
decltype(fun) f = fun; // ERROR
f();
}
The error is:
prog.cc: In function 'int main()':
prog.cc:19:19: warning: declaration of 'int f()' has 'extern' and is initialized
decltype(fun) f = fun; // ERROR
^
prog.cc:19:23: error: function 'int f()' is initialized like a variable
decltype(fun) f = fun; // ERROR
^~~
Wandbox URL: https://wandbox.org/permlink/E7BbGlyQD8FcHr5j
Here is essentially the same error without using decltype:
#include <iostream>
using namespace std;
int fun()
{
cout << "inside fun" << endl;
return 1;
}
int main()
{
// was: decltype(fun()) x = 2;
int x = 2;
cout << x << endl;
auto lambda = [] () -> int { cout << "inside lambda" << endl; return 3; };
decltype(lambda) l = lambda;
l();
typedef int fn_type();
fn_type* f = fun; // no problem
fn_type g = fun; // ERROR
f();
}
You have declared f to be of type int() i.e. it's like you're trying to copy the function into a new variable, which C++ does not support (functions are not first-class objects). It's permissible to create a function pointer, which is probably what you want, and assign directly from fun, which will be automatically treated as a function pointer in that context.
This doesn't happen for lambdas because they implicitly declare a new class (just a regular class in the usual sense). They act like functions because they have an overloaded operator() method, but they are not actually functions in the traditional C++ sense.
decltype(fun) returns the function type, not the fn ptr type. You can't 'assign' a function, only a function ptr. If you want to wrap a free function, you have these choices:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With