C++ 尝试使用的std::result\u时发生编译错误
我想推断作为模板参数的函数的返回类型。考虑下面的代码:C++ 尝试使用的std::result\u时发生编译错误,c++,c++11,typetraits,C++,C++11,Typetraits,我想推断作为模板参数的函数的返回类型。考虑下面的代码: #include <type_traits> struct Result {}; Result foo() { return Result{}; } template<typename Factory> void check(Factory) { using ActualResult = typename std::result_of<Factory()>::type; static
#include <type_traits>
struct Result {};
Result foo() { return Result{}; }
template<typename Factory>
void check(Factory) {
using ActualResult = typename std::result_of<Factory()>::type;
static_assert(std::is_same<Result, ActualResult>::value, "");
}
int main() {
check(foo);
}
这里有什么问题?如何使其工作?函数(就像数组一样)既不能作为prvalue参数传递,也不能作为prvalue返回
因此,template void check(Factory)
采用prvalue参数,将导致foo
衰减到函数指针,而check(foo)
将导致Factory
推断为结果(*)(
)。最后,的result\u给出调用可调用类型的结果,该类型是不带参数的函数指针
当您将check
更改为check(const Factory&)
时,函数采用左值,因此没有衰减,Factory
被推断为函数类型Result()
。这不是允许传递给
*的result\u的类型,它需要可调用类型或对函数的引用。也就是说,在这种情况下,您应该使用
的result\u
*)在C++11中。在以后的版本中,
的result\u规则可能已经放宽,C++17不赞成的result\u@petersohn:啊,是的,这实际上在两种情况下都有效。
prog.cc: In instantiation of 'void check(const Factory&) [with Factory = Result()]':
prog.cc:14:14: required from here
prog.cc:9:66: error: function returning a function
using ActualResult = typename std::result_of<Factory()>::type;
^
prog.cc:10:65: error: function returning a function
static_assert(std::is_same<Result, ActualResult>::value, "");
^