#include <iostream>
#include <type_traits>
#include <iomanip>
using namespace std;
template<typename T>
bool f(T&& v)
{
return is_function_v<decltype(forward<T>(v))>;
}
int main()
{
cout << boolalpha
<< is_function_v<decltype(setw)>
<< endl;
cout << boolalpha
<< f(setw)
<< endl;
return 0;
}
输出为:(clang 6.0&gcc 8.0)
>
真正
假
但我期望的结果应该是:
>
真正
真正
为什么std::is_function_v
不能按预期工作?
您需要删除T
上的参考。
template<typename T>
bool f(T&& v)
{
return is_function_v<remove_reference_t<decltype(forward<T>(v))>>;
// ~~~~~~~~~~~~~~~~~~
}
当将setw
传递给f
时,它是一个左值,然后转发引用类型T
将被推断为函数的左值引用。对于std::is_function
,函数(和函数指针等)的引用不算作函数类型。
顺便说一句:转发参考类型T
将推导为左值参考或右值参考;并且在decltype
上使用std::forward
将始终产生一个引用类型,左值引用或右值引用。