为什么 std::is_function<F> 在推导 F 时返回 false_type?
Why does std::is_function<F> return false_type when F is deduced?
给定以下代码,其中自动推导出类型Function
,当我断言Function
是否是使用 std::is_function<Function>
的函数时,我得到了意想不到的结果:
#include <iostream>
#include <iomanip>
#include <type_traits>
template <typename Function>
bool test_type(Function&& f)
{
return std::is_function<Function>::value;
}
template <typename Function>
bool test_decltype(Function&& f)
{
return std::is_function<decltype(f)>::value;
}
int f()
{
return 1;
}
int main()
{
std::cout << std::boolalpha
<< "is_function<Function>: " << test_type(f) << std::endl
<< "is_function<decltype(f)>: " << test_decltype(f) << std::endl
<< std::endl
<< "Explicit type:" << std::endl
<< "is_function<Function>: " << test_type<int()>(f) << std::endl
<< "is_function<decltype(f)>: " << test_decltype<int()>(f) << std::endl;
return 0;
}
然而,结果是(这里:http://ideone.com/Jy1sFA,使用 MSVC2013.4 在本地验证):
is_function<Function>: false
is_function<decltype(f)>: false
Explicit type:
is_function<Function>: true
is_function<decltype(f)>: false
我希望即使在推断的情况下is_function<Function>
也会true_type
。老实说,我什至希望is_function<decltype(f)>
在这两种情况下都true_type
,但唉,事实并非如此。
对于您的类型,您可以使用std::remove_reference
的额外参考:
template <typename Function>
bool test_type(Function&& f)
{
return std::is_function<typename std::remove_reference<Function>::type>::value;
}
template <typename Function>
bool test_decltype(Function&& f)
{
return std::is_function<typename std::remove_reference<decltype(f)>::type>::value;
}
现场示例
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- 将内存分配返回值强制转换为 TYPE 数组
- 返回的向量定义为 "std::vector<<error-type>, std::allocator<<error-type>>>
- 如何使用 enable_if<>::type 返回类型对函数进行原型设计?
- 自动返回类型哪个更好:decltype 或 std::common_type<>::type(如果可能)?
- 指向 c++ 中具有自动返回'type'的模板成员的指针?
- getaddrinfo() 返回错误"The requested name is valid, but no data of the requested type was found."
- CMSIS-RTOS 的 osMailFree() 返回一些地址而不是 osStatus-type 值
- 返回 type of const int &
- 返回"does not name type"的模板化类
- 错误:"dependent name is not a type" 。当在类中使用 typedef 类型作为返回值时,带有模板
- Decltype (auto),尾随返回type和sfinae:可以混合使用吗?
- 为什么QVariant::type()返回一个QVariant::type,而它应该被解释为QMetaType:: ty
- 在同一类的方法中返回对象的Type
- new(size, value) Type[0]返回的指针是否合法,是否可以用来构建数组?