result_of 无法推断出 return 类型
result_of fails to deduce return type
以下代码无法在 GCC 5.2 中编译:
template<typename FuncType, typename... ArgTypes>
result_of_t<FuncType(ArgTypes...)> FuncCall(const FuncType &f, ArgTypes&... args)
{
return f(forward<ArgTypes>(args)...);
}
string SomeFunc()
{
return "SomeFunc";
}
int main()
{
cout << FuncCall([](){return "Lambda";}) << "\n"; // This call works properly
cout << FuncCall(SomeFunc) << "\n"; // this call fails
}
但如果我更改以下行:
result_of_t<FuncType(ArgTypes...)> FuncCall(const FuncType &f, ArgTypes&... args)
到
result_of_t<FuncType&&(ArgTypes...)> FuncCall(const FuncType &f, ArgTypes&... args)
然后就正常了
我不明白在这种情况下创建 FuncType 右值引用是如何解决问题的。任何人都可以分享一些关于这方面的信息吗?
C++ 中的函数类型可能没有作为函数类型的 return 类型,[dcl.fct]/10:
Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things.
所以当 FuncType
被推导为函数类型时,声称的类型 FuncType(Args...)
是错误的。
以下代码无法在 GCC 5.2 中编译:
template<typename FuncType, typename... ArgTypes>
result_of_t<FuncType(ArgTypes...)> FuncCall(const FuncType &f, ArgTypes&... args)
{
return f(forward<ArgTypes>(args)...);
}
string SomeFunc()
{
return "SomeFunc";
}
int main()
{
cout << FuncCall([](){return "Lambda";}) << "\n"; // This call works properly
cout << FuncCall(SomeFunc) << "\n"; // this call fails
}
但如果我更改以下行:
result_of_t<FuncType(ArgTypes...)> FuncCall(const FuncType &f, ArgTypes&... args)
到
result_of_t<FuncType&&(ArgTypes...)> FuncCall(const FuncType &f, ArgTypes&... args)
然后就正常了
我不明白在这种情况下创建 FuncType 右值引用是如何解决问题的。任何人都可以分享一些关于这方面的信息吗?
C++ 中的函数类型可能没有作为函数类型的 return 类型,[dcl.fct]/10:
Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things.
所以当 FuncType
被推导为函数类型时,声称的类型 FuncType(Args...)
是错误的。