显然,你可以使用decltype(foo())获取函数的返回类型,但是如果foo接受不起作用的参数,你必须将一些伪参数传递给foo才能使它工作.但是,有没有办法获得函数的返回类型而不必传递任何参数?
C++ 11提供std::result_of
.
http://en.cppreference.com/w/cpp/types/result_of
在函数接受参数的情况下,您可以提供"虚拟"参数std::declval
.
http://en.cppreference.com/w/cpp/utility/declval
假设返回类型不依赖于参数类型(在这种情况下你应该使用类似的东西std::result_of
,但你必须提供这些参数的类型),你可以编写一个简单的类型特征,让你从中推断出返回类型.功能类型:
#include <type_traits>
template<typename T>
struct return_type;
template<typename R, typename... Args>
struct return_type<R(Args...)>
{
using type = R;
};
int foo(double, int);
int main()
{
using return_of_foo = return_type<decltype(foo)>::type;
static_assert(std::is_same<return_of_foo, int>::value, "!");
}
Run Code Online (Sandbox Code Playgroud)