decltype(*&fun)很奇怪吗?

decltype(*&fun) is strange?

本文关键字:fun decltype      更新时间:2023-10-16

我有:

#include <type_traits>
#include <stdio.h>
void f() { printf("foon"); }
int main()
{
  printf("%d %d %dn",
    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

关于g++4.6.1和4.7.0。

有人能向我解释一下吗?

需要注意的是,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)