result_of主要用于目标函数定义的类型推导中,在C++中auto也会自动推导类型,但是初始值不赋值时,auto是不能推导出目标类型,但result_of是可以推导出类型。
result_of的用法如下:
template
struct result_of
模板参数:
(1)Fn
可调用类型(即函数对象类型或指向成员的指针),或对函数的引用,或对可调用类型的引用。
(2)ArgTypes
类型列表,与调用中的顺序相同。
请注意,模板参数不是逗号分隔的,而是函数形式的。
成员类型:
(1)type
使用 ArgTypes 中指定类型的参数调用 Fn 的结果类型。
总述:
使用result_of推导的类型是函数Fn(ArgTypes...)的返回类型。
demo如下:
// result_of example #include#include int fn(int) {return int();} // function typedef int(&fn_ref)(int); // function reference typedef int(*fn_ptr)(int); // function pointer struct fn_class { int operator()(int i){return i;} }; // function-like class int main() { typedef std::result_of ::type A; // int,其中decltype(funName)返回函数funName的函数类型 typedef std::result_of ::type B; // int typedef std::result_of ::type C; // int typedef std::result_of ::type D; // int std::cout << std::boolalpha; std::cout << "typedefs of int:" << std::endl; std::cout << "A: " << std::is_same ::value << std::endl; std::cout << "B: " << std::is_same ::value << std::endl; std::cout << "C: " << std::is_same ::value << std::endl; std::cout << "D: " << std::is_same ::value << std::endl; return 0; }
知识链接如下:
上述demo的代码参考于result_of - C++ Reference (cplusplus.com)http://www.cplusplus.com/reference/type_traits/result_of/
上述代码中typedef的用法见C++ typedef用法详解 - seventhsaint - 博客园 (cnblogs.com)https://www.cnblogs.com/seventhsaint/archive/2012/11/18/2805660.html
上述代码中decltype的用法见
C++11的std::declval与decltype_hanxiaoyong_的博客-CSDN博客https://blog.csdn.net/hanxiaoyong_/article/details/120123056



