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

问题描述 投票:5回答:1

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

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

#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类型的正确语法是什么?

c++ templates typetraits invoke-result
1个回答
4
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.