I have:
#include <type_traits>
#include <stdio.h>
void f() { printf("foo\n"); }
int main()
{
printf("%d %d %d\n",
std::is_same<decltype(*&f),decltype(f)>::value,
std::is_function<decltype(*&f)>::value,
std::is_function<decltype(f)>::value);
(*&f)();
return 0;
}
which yields
0 0 1
foo
on g++ 4.6.1 and 4.7.0.
Can anyone explain this to me?
It's important to note that decltype
has two meanings: it can be used to find the declared type (hence its name) of an entity, or it can be used to inspect an expression. I'm using entity loosely here and am not referring to any term of the Standard but to put it simply it could be a variable, a function, or (strangely enough in my opinion) a member access. The type that is returned when an expression is examined is more often than not different from the type of the expression itself, thus:
int i;
void foo();
struct { int i; } t;
static_assert( std::is_same<decltype( i ), int>::value, "" );
static_assert( std::is_same<decltype( foo ), void()>::value, "" );
static_assert( std::is_same<decltype( t.i ), int>::value, "" );
static_assert( std::is_same<decltype( (i) ), int&>::value, "" );
static_assert( std::is_same<decltype( (foo) ), void(&)()>::value, "" );
static_assert( std::is_same<decltype( (t.i) ), int&>::value, "" );
Note how this works for functions, and hence that in your case decltype(*&f)
is the same as decltype( (f) )
, not decltype(f)
.
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