invoke_result获取模板成员函数的返回类型

时间:2019-12-10 12:58:39

标签: c++ templates typetraits invoke-result

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

下面的最小示例说明了该问题。

#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;

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

1 个答案:

答案 0 :(得分:5)

您可以得到如下返回类型:

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移出类应该有帮助。