获取C ++ 11中函数的结果类型 [英] Get the result type of a function in c++11

查看:58
本文介绍了获取C ++ 11中函数的结果类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑C ++ 11中的以下功能:

Consider the following function in C++11:

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

我希望 ReturnType 等于结果类型 f(args ...)
我必须写些什么,而不是 / * SOMETHING * /

I want ReturnType to be equal to the result type of f(args...) What do I have to write instead of /*SOMETHING*/ ?

推荐答案

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

I think you should rewrite your function template using trailing-return-type as:

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.
}

请注意,如果您通过 args Args&& ... 而不是 const Args&.... ,那么它就是最好将 f 中的 std :: forward 用作:

Note that if you pass args as Args&&... instead of const Args&...., then it is better to use std::forward in f as:

decltype(f(std::forward<Args>(args)...))

当您使用 const Args& ... 时,然后使用 std :: forward

When you use const Args&..., then std::forward doesn't make much sense (at least to me).

最好将 args 传递为 Args& .. 称为 universal-reference ,并使用 std :: forward

It is better to pass args as Args&&.. called universal-reference and use std::forward with it.

这篇关于获取C ++ 11中函数的结果类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆