繁体   English   中英

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

[英]invoke_result to obtain return type of template member function

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

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

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

代码不编译,报错:

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

11 | 使用 default_return_type = std::invoke_result_t;

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM