使用std::result_of确定模板实参的返回类型
using std::result_of to determine the return type of a template argument
我认为这段代码是不言自明的,但基本上模板函数ExecFunc
应该能够执行另一个函数并返回其结果。我知道我可以使用decltype
而不是result_of
达到类似的结果,但这个问题是为了理解为什么我所写的不工作:代码片段不能在gcc v4.9.2上编译。
这是我的:
#include <type_traits>
int f(int i)
{
return i;
}
template<class F, class T>
auto ExecFunc(F f, T arg) -> typename std::result_of<F()>::type
{
return f(arg);
}
int main() {
auto a = ExecFunc(f, 3);
return 0;
}
,这是编译器的输出:
prova.cpp: In function ‘int main()’:
prova.cpp:15:26: error: no matching function for call to ‘ExecFunc(int (&)(int), int)’
auto a = ExecFunc(f, 3);
^
prova.cpp:15:26: note: candidate is:
prova.cpp:9:6: note: template<class F, class T> typename std::result_of<F()>::type ExecFunc(F, T)
auto ExecFunc(F f, T arg) -> typename std::result_of<F()>::type
^
prova.cpp:9:6: note: template argument deduction/substitution failed:
prova.cpp: In substitution of ‘template<class F, class T> typename std::result_of<F()>::type ExecFunc(F, T) [with F = int (*)(int); T = int]’:
prova.cpp:15:26: required from here
prova.cpp:9:6: error: no type named ‘type’ in ‘class std::result_of<int (*())(int)>’
注意:这个问题可能看起来像这个问题的副本,但接受的解决方案对我不起作用(至少,据我所知,我已经将解决方案纳入了我的代码中)。
您的函数是int f(int i)
,但您正在调用F()
,这是未知的。std::result_of<F()>::type
应该是std::result_of<F(T)>::type
生活例子
问题是result_of
的参数,它应该是:
-> typename std::result_of<F(T)>::type
这是使用decltype
template<class F, class T>
auto ExecFunc(F f, T arg) -> decltype(f(arg))
相关文章:
- 如何获取std::result_of函数的返回类型
- 奇怪的结构&GCC&clang(void*返回类型)
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 为什么与常规GCC不同,即使有"学究性错误",MinGW-GCC也能容忍丢失的返回类型
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 函数作为模板参数,是否对返回类型强制约束
- 非类型引用形参/实参
- 函数模板中返回类型的模板实参演绎
- 模板类的不同返回类型取决于类的形参
- c++临时对象绑定到实参并返回const引用值
- 为什么模板非类型形参指针和引用实参需要是全局的
- 对于每个模板类型,都有一个集合类型的实参
- 当对象类型为模板实参时,是否有办法将模板实参传递给对象上的函数
- 将非const引用使用auto-keyword声明的lambda作为实参传递给std::函数形参类型
- 是否存在允许将非const模板实参类型隐式转换为const的规范方法?
- 使用std::result_of确定模板实参的返回类型
- 函数指针的形参类型的模板实参演绎涉及未演绎的形参包
- 从函数指针的实参中演绎出c++模板类型
- 非类型形参取决于它后面的实参