如何在C ++ 11中为result_of编写帮助类型 [英] How to write a helper type for result_of in C++11
问题描述
template<typename F,typename...X>
using Result_of = typename result_of<F(X...)>::type;
int ff(int){return 2;}
typedef bool(*PF)(int);
auto fx = [](char ch){return tolower(ch);};
Result_of<decltype(&ff)()> r1 = 7;
Result_of<PF(int)> r2 = 2;
Result_of<decltype(fx)(char)> r5 = "a";
当我用gcc编译时,得到以下错误:
When I compile with gcc, I get the following error:
main.cpp: In substitution of 'template<class F, class ... X> using Result_of = typename std::result_of<_Functor(_ArgTypes ...)>::type [with F = int (*())(int); X = {}]':
main.cpp:17:30: required from here
main.cpp:6:57: error: function returning a function
using Result_of = typename std::result_of<F(X...)>::type;
^
为什么我收到此错误,如何解决? >
Why am I getting this error and how do I fix it?
推荐答案
这行有几个问题:
Result_of<decltype(&ff)()> r1 = 7;
首先, Result_of
采用函数类型参数列表,以逗号分隔。你不是这样提供的。因此,它将 F
解释为(int)(*)(int)()
一个函数 int
返回一个返回 int
的函数。但是在C ++中有一个函数返回一个函数是非法的,因此错误。
First, Result_of
takes a function type and a list of arguments, comma separated. You're not providing them that way. So it's interpreting F
to be (int)(*)(int)()
, which would be a pointer to a function taking an int
returning a function returning an int
. But it's illegal in C++ to have a function return a function, hence the error.
其次, ff
接受 int
。最后, ff
衰减到指针函数,您需要实际的函数。正确的表达式是:
Second, ff
takes an int
, not nothing. Lastly, ff
decays to a pointer-to-function and you need the actual function. The correct expression would be:
Result_of<decltype(*ff), int> r1 = 7;
同样,下一个需要是:
Result_of<PF, int> r2 = 2;
Result_of<decltype(fx), char> r5 = 'a'; // fx returns an int, so you
// can't assign a const char* to it
这篇关于如何在C ++ 11中为result_of编写帮助类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!