如何获取模板成员函数的结果类型?
下面的最小示例说明了该问题。
#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;
}
See it live https://coliru.stacked-crooked.com/a/4edac6bf0866f2b6在科利鲁上。
代码无法编译,报错:
main.cpp:11:63: 错误:decltype 无法解析重载的地址
功能
11 | 11使用default_return_type =
std::invoke_result_t;
获取类型的正确语法是什么B::f
与模板参数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
走出课堂应该有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)