decltype(*& fun)很奇怪?

时间:2012-02-27 15:42:22

标签: c++ g++ c++11 decltype

我有:

#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;
}

产生

0 0 1
foo

on g ++ 4.6.1和4.7.0。

任何人都可以向我解释这个吗?

1 个答案:

答案 0 :(得分:13)

重要的是要注意decltype有两个含义:它可用于查找实体的声明类型(因此其名称),或者它可用于检查表达。我在这里松散地使用实体,并不是指标准的任何术语,而是简单地说它可以是变量,函数,或者(在我看来,奇怪的是)成员访问。检查表达式时返回的类型通常与表达式本身的类型不同,因此:

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,      "" );

请注意这对函数有何用处,因此在您的情况下decltype(*&f)decltype( (f) )相同,而不是decltype(f)