【问题标题】:no type named "type" in "std::result_of" ; get return type from overloading functions"std::result_of" 中没有名为 "type" 的类型;从重载函数中获取返回类型
【发布时间】:2017-02-16 09:27:03
【问题描述】:

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

我从a SO answer (by 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;
}

我得到一个编译错误。

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

据我了解:-

  • TestType&lt;...&gt; 是“可变参数模板”。
    用我自己的话来说,它就像一个压缩的缩写,有任意数量的参数。

  • TestType&lt;double&gt;test(double) 函数的id

  • std::result_of&lt;TestType&lt;double&gt;&gt;::typetest(double) 的返回类型。
    doubleDat 应该是 double

问题:为什么不能编译?如何解决?

我已经阅读了这些:-

线索:经过长时间的搜索,我隐隐约约感觉到我的代码遭受了“最烦人的解析”。

【问题讨论】:

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


    【解决方案1】:

    看看你的TestType&lt;double&gt; 扩展成什么:

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

    test(std::decvlal&lt;double&gt;)double 所以你得到double(double)

    result_of&lt;double(double)&gt;::type 询问您是否可以使用double 类型的参数调用double

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

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

    这样就可以了:

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

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

    【讨论】:

    • 实验后正要写自己的答案。你打败了我。
    • 我想擅长这些事情。 (我是在慢慢摸索的基础上学习的。)如何在一大块中获得这方面的丰富知识?有没有书,例如an C++ book SO link 中的哪一个,深入涵盖了这些主题?教程视频?你会写一些 C++ 书籍吗?
    • 谢谢。我想我现在必须穿上盔甲了。
    猜你喜欢
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 2014-11-03
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多