“ fun”和“&fun”之间的类型差异?
收藏

Do expressions fun and &fun have the same type or not?

考虑以下代码:

template <typename Check, typename T>
void check(T)
{
    static_assert(is_same<Check, T>::value);
}

void fun()
{}

check<void(*)()>(fun);
check<void(*)()>(&fun);

cout << typeid(fun).name() << endl;
cout << typeid(&fun).name() << endl;

Both assertions succeed which suggests that both expressions have the same type. However, typeids return different results:

FvvE
PFvvE

这是为什么?

最佳答案

Both assertions succeed because they are applied to the type T deduced from function argument. In both cases it will be deduced as a pointer to function because functions decay to a pointer to function. However if you rewrite assertions to accept types directly then first one will fail:

static_assert(is_same<void(*)(), decltype(fun)>::value);
static_assert(is_same<void(*)(), decltype(&fun)>::value);

在线编译器

    公众号
    关注公众号订阅更多技术干货!