Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decltype(*&fun) is strange?

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?

like image 901
smilingthax Avatar asked Dec 13 '22 05:12

smilingthax


1 Answers

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).

like image 168
Luc Danton Avatar answered Dec 30 '22 10:12

Luc Danton