如何获取模板成员函数的结果类型?
下面的最小示例说明了该问题。
#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
类型的正确语法是什么?
答案 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
移出类应该有帮助。