decltype(*&fun) is strange?

无人久伴 提交于 2019-12-22 08:42:09

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/9467791/decltypefun-is-strange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!