确定函数返回类型的最简单方法

Cyb*_*ran 48 c++ function return-type compile-time c++17

给出一个非常简单但冗长的功能,例如:

int foo(int a, int b, int c, int d) {
    return 1;
}

// using ReturnTypeOfFoo = ???
Run Code Online (Sandbox Code Playgroud)

在编译时确定函数返回类型(ReturnTypeOfFoo在本例中int为:) 的最简单,最简洁的方法是什么,而不重复函数的参数类型(仅限名称,因为已知该函数没有任何额外的重载)?

Nat*_*ica 56

你可以利用std::function这里给你一个函数返回类型的typedef.这确实需要C++ 17支持,因为它依赖于类模板参数推导,但它适用于任何可调用类型:

using ReturnTypeOfFoo = decltype(std::function{foo})::result_type;
Run Code Online (Sandbox Code Playgroud)

我们可以使这更像一般

template<typename Callable>
using return_type_of_t = 
    typename decltype(std::function{std::declval<Callable>()})::result_type;
Run Code Online (Sandbox Code Playgroud)

然后让你像使用它一样

int foo(int a, int b, int c, int d) {
    return 1;
}

auto bar = [](){ return 1; };

struct baz_ 
{ 
    double operator()(){ return 0; } 
} baz;

using ReturnTypeOfFoo = return_type_of_t<decltype(foo)>;
using ReturnTypeOfBar = return_type_of_t<decltype(bar)>;
using ReturnTypeOfBaz = return_type_of_t<decltype(baz)>;
Run Code Online (Sandbox Code Playgroud)

  • 在 C++17 中:“使用 ReturnType = std::invoke_result_t&lt;decltype(foo)&gt;;” (7认同)

Bar*_*rry 22

最简单和简洁的可能是:

template <typename R, typename... Args>
R return_type_of(R(*)(Args...));

using ReturnTypeOfFoo = decltype(return_type_of(foo));
Run Code Online (Sandbox Code Playgroud)

请注意,这不适用于函数对象或指向成员函数的指针.只是功能,没有重载或模板,或noexcept.

但是,如果需要,可以通过添加更多的重载来扩展以支持所有这些情况return_type_of.


max*_*x66 15

我不知道是否是最简单的方法(如果你可以使用C++ 17肯定不是:请参阅NathanOliver的答案)但是......如何声明一个函数如下:

template <typename R, typename ... Args>
R getRetType (R(*)(Args...));
Run Code Online (Sandbox Code Playgroud)

和使用decltype()

using ReturnTypeOfFoo = decltype( getRetType(&foo) );
Run Code Online (Sandbox Code Playgroud)

观察它getRetType()只是声明和未定义因为只调用a decltype(),所以只有返回的类型是相关的.