是否可以在不传递参数的情况下获得函数的返回类型?
很显然,您可以使用decltype(foo())获得函数的返回类型,但是如果foo接受了无效的参数,则必须将一些虚拟参数传递给foo才能使其正常工作.但是,有没有一种方法可以获取函数的返回类型而不必传递任何参数呢?
Obviously, you can get the return type of a function with decltype(foo()), but if foo takes arguments that won't work, you'd have to pass some dummy arguments to foo in order for it to work. But, is there a way to get the return type of a function without having to pass it any arguments?
假定返回类型不取决于参数类型(在这种情况下,您应该使用 std :: result_of
之类的东西,但是您必须提供这些参数的类型),您可以编写一个简单的类型特征,让您从函数类型中推断出返回类型:
Supposing the return type does not depend on the argument type (in which case you should use something like std::result_of
, but you would have to provide the type of those arguments), you can write a simple type trait that lets you deduce the return type from the function type:
#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, "!");
}