void foo(int a) {
cout << "Hello" << a << '\n';
}
according to rule of decltype, the type of decltype(foo) should be "void foo(int)", but it seems we can do nothing with it:
void (& f_ref)(int) = foo;
void (* f_ptr)(int) = foo;
cout<<is_same_v<decltype(foo), decltype(f_ref)><<endl; //return 0
cout<<is_same_v<decltype(foo), decltype(f_ptr)><<endl; //return 0
decltype(foo) df;
df = foo; //error: assignment of function ‘void df(int)’
df = &foo; //error: assignment of function ‘void df(int)’
decltype(foo) df{foo}; //error: function ‘void df(int)’ is initialized like a variable
decltype(foo) df{&foo}; //error: function ‘void df(int)’ is initialized like a variable
Two is_same_v
in your snippets are evaluated as 0
because, well, the types are different.
dectype(foo)
is void (int)
(not void foo(int)
, the name is not a part of the type),
which is different from void (&)(int)
(the type of f_ref
) and void (*)(int)
(the type of f_ptr
).
This line:
decltype(foo) df{foo};
doesn't compile just because the syntax doesn't allow you to have initializers in function declarations.
Even without the decltype
it doesn't work:
void df(int) {foo}; // error: expected ';' before '}' token
Though you can create a pointer to decltype(foo)
:
decltype(foo) *df{foo}; // Becomes `void (*df)(int) {foo};`
These lines:
df = foo;
df = &foo;
don't compile because you can't assign to functions. It wouldn't work even if df
was void df(int);
.
There are countless uses. E.g. you can use it to create pointers to this function as mentioned above, or it can be used as a template parameter (for std::function
or something else).