【问题标题】:invoke_result to obtain return type of template member functioninvoke_result 获取模板成员函数的返回类型
【发布时间】:2019-12-10 12:58:39
【问题描述】:

如何获取模板成员函数的结果类型?

以下最小示例说明了问题。

#include <type_traits>

template <typename U>
struct A {
};

struct B {
   template <typename F = int>
   A<F> f() { return A<F>{}; }

   using default_return_type = std::invoke_result_t<decltype(f)>;
};

int main()
{
    B::default_return_type x{};

    return 0;
}

在 Coliru 上查看 live

代码没有编译,报错:

main.cpp:11:63: 错误:decltype 无法解析重载地址 功能

11 |使用 default_return_type = std::invoke_result_t;

在模板参数F设置为默认值的情况下,获取B::f类型的正确语法是什么?

【问题讨论】:

    标签: c++ templates typetraits invoke-result


    【解决方案1】:

    你可以像这样得到返回类型:

    using default_return_type = decltype(std::declval<B>().f());
    

    完整示例:

    #include <type_traits>
    #include <iostream>
    template <typename U>
    struct A {
    };
    
    struct B {
       template <typename F = int>
       A<F> f() { return A<F>{}; }
    
       using default_return_type = decltype(std::declval<B>().f());
    };
    
    int main()
    {
        B::default_return_type x{};
        std::cout << std::is_same< B::default_return_type, A<int>>::value;
    }
    

    PS:clang 和较旧的 gcc 版本似乎对 B 是一个不完整的类型并调用 f 不满意。作为一种解决方法,将using 移出课堂应该会有所帮助。

    【讨论】:

    • 我也试过了,但我得到“成员访问不完整类型 B”
    • @max66 哪个编译器?
    • @max66 hm 很有趣,例如 gcc7.3.0 失败,但 gcc 9.2 没问题
    • 铿锵头10.0.0.
    • @max66 开了一个新问题澄清stackoverflow.com/questions/59268030/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多