在“ std :: result_of”中没有名为“ type”的类型;从重载函数获取返回类型

jav*_*ver 0 overloading result-of decltype variadic-templates c++11

我正在学习如何获得type重载函数test()vs 的返回值test(double)

我从SO答案(由chris)修改了代码。

#include <type_traits>
#include <utility>

int test();
double test(double x);

template<typename... Ts>
using TestType = decltype(test(std::declval<Ts>()...))(Ts...);

int main() {
    std::result_of< TestType<double> >::type n = 0;
     //^ ### compile error ###
    using doubleDat = std::result_of< TestType<double> >::type ;
    doubleDat n=0;
}
Run Code Online (Sandbox Code Playgroud)

我遇到了编译错误。

错误:“ std :: result_of”中没有名为“ type”的类型

我认为:-

  • TestType<...>是“可变模板”。
    用我自己的话说,它就像一个带有任何参数的压缩缩写

  • TestType<double>ID的的test(double)功能。

  • std::result_of<TestType<double>>::type是的返回类型test(double)
    doubleDat应该是double

问题:为什么不编译?怎么解决呢?

我读过这些:

线索:经过长时间的搜索,我隐隐感到我的代码遭受“最令人讨厌的解析”。

Jon*_*ely 5

查看您TestType<double>扩展到的内容:

test(std::declval<double>())(double)
Run Code Online (Sandbox Code Playgroud)

test(std::decvlal<double>)是,double所以你得到double(double)

result_of<double(double)>::type询问您是否可以double使用类型为的参数调用double

答案是否定的,因为double它不可调用,所以没有嵌套类型。

您需要阅读文档result_of以了解如何使用它。类型result_of<F(Arg)>::typeF使用参数调用的结果Arg。如果F可以用参数调用,Arg则返回类型;如果不能用参数调用,Arg则嵌套type不存在。

所以这可以工作:

using func_type = TestType<double>;
using doubleDat = std::result_of<func_type*(double)>::type;
Run Code Online (Sandbox Code Playgroud)

这将为类型TestType<double>(即double(double))的函数创建一个别名,然后询问您是否可以使用类型double(*)(double)为实参的类型调用指向该类型的指针(即)double。而且您可以,所以您type有效。