gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:57:25 26 4
gpt4 key购买 nike

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

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

我希望 ReturnType 等于 f(args...) 的结果类型我必须写什么来代替 /*SOMETHING*/

最佳答案

我认为您应该使用 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.
}

请注意,如果您通过 args作为Args&&...而不是 const Args&... , 那么最好使用 std::forwardf作为:

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

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

最好通过args作为Args&&...称为 universal-reference 并使用 std::forward与它。

关于c++ - 获取c++11中函数的结果类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14144573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com