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

fra*_*sco 6 c++ templates type-traits 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;
}
Run Code Online (Sandbox Code Playgroud)

看到它在Coliru。

代码不编译,报错:

main.cpp:11:63: 错误:decltype 无法解析重载函数的地址

11 | 使用 default_return_type = std::invoke_result_t;

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

for*_*818 5

您可以像这样获得返回类型:

using default_return_type = decltype(std::declval<B>().f());
Run Code Online (Sandbox Code Playgroud)

完整示例:

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • @max66提出了一个新问题来澄清/sf/ask/4148762131/ (2认同)