在c ++ 11中获取函数的结果类型

Vin*_*ent 4 c++ templates type-traits c++11

考虑C++ 11中的以下函数:

template<class Function, class... Args, typename ReturnType = /*SOMETHING*/> 
inline ReturnType apply(Function&& f, const Args&... args);
Run Code Online (Sandbox Code Playgroud)

我想ReturnType等于f(args...) 我必须写的结果类型而不是/*SOMETHING*/

Naw*_*waz 14

我认为你应该使用trailing-return-type重写你的函数模板:

template<class Function, class... Args> 
inline auto apply(Function&& f, const Args&... args) -> decltype(f(args...))
{
    typedef decltype(f(args...)) ReturnType;

    //your code; you can use the above typedef.
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果你传递args作为Args&&...代替 const Args&....,那么最好是使用std::forwardf如:

decltype(f(std::forward<Args>(args)...))
Run Code Online (Sandbox Code Playgroud)

当你使用时const Args&...,std::forward没有多大意义(至少对我而言).

最好是通过args作为Args&&..所谓的通用参考,并使用std::forward它.