invoke_result获取return类型的模板成员函数
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 上 live 查看。
代码无法编译,报错:
main.cpp:11:63: error: decltype cannot resolve address of overloaded
function
11 | using default_return_type =
std::invoke_result_t;
在模板参数 F
设置为默认值的情况下获取 B::f
类型的正确语法是什么?
您可以获得这样的 return 类型:
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
移出 class 应该会有所帮助。
如何获取模板成员函数的结果类型?
下面的最小示例说明了这个问题。
#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: error: decltype cannot resolve address of overloaded function
11 | using default_return_type = std::invoke_result_t;
在模板参数 F
设置为默认值的情况下获取 B::f
类型的正确语法是什么?
您可以获得这样的 return 类型:
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
移出 class 应该会有所帮助。