是否有可能在不传递参数的情况下获得函数的返回类型?

Is it possible to get the return type of a function without passing arguments to it?

本文关键字:情况下 函数 返回类型 参数 有可能 是否      更新时间:2023-10-16

显然,您可以使用decltype(foo())获得函数的返回类型,但如果foo接受的参数不起作用,则必须传递一些虚拟参数给foo以使其工作。但是,有没有一种方法可以在不传递任何参数的情况下获得函数的返回类型?

假设返回类型不依赖于参数类型(在这种情况下,您应该使用类似std::result_of的东西,但您必须提供这些参数的类型),您可以编写一个简单的类型trait,使您可以从函数类型推断返回类型:

#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, "!");
}

c++ 11提供std::result_of

http://en.cppreference.com/w/cpp/types/result_of

在函数接受参数的情况下,您可以使用std::declval提供"假"参数。

http://en.cppreference.com/w/cpp/utility/declval

相关文章: