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

时间:2017-02-16 09:27:04

标签: c++11 variadic-templates overloading decltype result-of

我正在学习如何获得重载函数 "aggregations" : { "players" : { "doc_count_error_upper_bound" : 0, "sum_other_doc_count" : 0, "buckets" : [ { "key" : 2, "doc_count" : 2, "maxscore" : { "hits" : { "total" : 2, "max_score" : null, "hits" : [ { "_index" : "xxxx:scores:1487236388", "_type" : "score", "_id" : "AVpGMlb1XRLwiv8C2uL2", "_score" : null, "_source" : { "player" : { "id" : 2, "name" : "Dan" }, "score" : 12 }, "sort" : [ 12 ] } ] } } }, { "key" : 1, "doc_count" : 1, "maxscore" : { "hits" : { "total" : 1, "max_score" : null, "hits" : [ { "_index" : "xxxx:scores:1487236388", "_type" : "score", "_id" : "AVpGMlb1XRLwiv8C2uL3", "_score" : null, "_source" : { "player" : { "id" : 1, "name" : "Dave" }, "score" : 14 }, "sort" : [ 14 ] } ] } } } ] } } type的返回值test()

我修改了a SO answer (by chris)的代码。

test(double)

我遇到了编译错误。

  

错误:没有名为' type'在' std :: result_of'

据我所知: -

  • #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; } 是&#34;可变参数模板&#34;。
    用我自己的话来说,它就像一个包含任何参数的压缩缩写

  • TestType<...>是<{1}}函数的 id

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

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

我读过这些: -

线索:经过长时间的搜索,我发现我的代码遭受了微弱的气味&#34;最令人烦恼的解析&#34;。

1 个答案:

答案 0 :(得分:4)

查看TestType<double>展开的内容:

test(std::declval<double>())(double)

test(std::decvlal<double>)double,因此您获得了double(double)

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

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

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

所以这会奏效:

using func_type = TestType<double>;
using doubleDat = std::result_of<func_type*(double)>::type;

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

相关问题