欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++ 17轉(zhuǎn)發(fā)一個函數(shù)調(diào)用的完美實現(xiàn)

 更新時間:2017年08月28日 09:49:13   作者:孫明琦  
這篇文章主要給大家介紹了關于C++ 17如何轉(zhuǎn)發(fā)一個函數(shù)調(diào)用的完美實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家學習或者使用C++17具有一定的參考學習價值,需要的朋友們下面跟著小編來一起學習學習吧。

前言

本文主要給大家介紹了關于C++17轉(zhuǎn)發(fā)一個函數(shù)調(diào)用的相關內(nèi)容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧。

方法如下

首先你靈光一閃:

#define WARP_CALL(fun, ...) fun(__VA_ARGS__)

不我們并不喜歡宏,擴展性太差了

template<class R, class T1, class T2, class T3>
R warp_call(R(*fun)(T1, T2, T3), T1 a, T2 b, T3 c)
{
 return fun(a, b, c);
}

如果你寫出來上面這段代碼,你肯定是從C轉(zhuǎn)過來的,C++還沒用熟??紤]callable object和C++11 variadic template特性用上:

template<class Fun, class... Args>
auto wrap_call(Fun f, Args... args) -> decltype(f(args...))
{
 return f(args...);
}

加上移動語義,返回值推導:

template<class Fun, class... Args>
auto wrap_call(Fun&& f, Args&&... args)
{
 return std::forward<Fun>(f)(std::forward<Args>(args)...);
}

auto返回值實際上會有參數(shù)被decay的問題,用decltype + 尾置返回值

template<class Fun, class... Args>
auto wrap_call(Fun&& f, Args&&... args)
 -> decltype(std::forward<Fun>(f)(std::forward<Args>(args)...))
{
 return std::forward<Fun>(f)(std::forward<Args>(args)...);
}

有了C++14,可以直接使用decltype(auto)

template<class Fun, class... Args>
decltype(auto) wrap_call(Fun&& f, Args&&... args)
{
 return std::forward<Fun>(f)(std::forward<Args>(args)...);
}

別忘了noexcept

template<class Fun, class... Args>
decltype(auto) wrap_call(Fun&& f, Args&&... args)
 noexcept(noexcept(std::forward<Fun>(f)(std::forward<Args>(args)...)))
{
 return std::forward<Fun>(f)(std::forward<Args>(args)...);
}

但是上面的函數(shù)不是SFINAE-friendly的,因為decltype(auto)返回值的函數(shù)并不能直接從函數(shù)簽名獲得返回值,而對這個函數(shù)進行返回值推導,是可能產(chǎn)生hard error打斷SFINAE的。所以最好手動寫返回值

template<class Fun, class... Args>
auto wrap_call(Fun&& f, Args&&... args)
 noexcept(noexcept(std::forward<Fun>(f)(std::forward<Args>(args)...)))
 -> decltype(std::forward<Fun>(f)(std::forward<Args>(args)...))
{
 return std::forward<Fun>(f)(std::forward<Args>(args)...);
}

我們還遺漏了啥?constexpr

template<class Fun, class... Args>
constexpr auto wrap_call(Fun&& f, Args&&... args)
 noexcept(noexcept(std::forward<Fun>(f)(std::forward<Args>(args)...)))
 -> decltype(std::forward<Fun>(f)(std::forward<Args>(args)...))
{
 return std::forward<Fun>(f)(std::forward<Args>(args)...);
}

上面是完美的

完美嗎?去看看std::invoke

總結

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關文章

最新評論