C++ 17轉(zhuǎn)發(fā)一個函數(shù)調(diào)用的完美實現(xiàn)
前言
本文主要給大家介紹了關于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)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
C語言 解決不用+、-、×、÷數(shù)字運算符做加法的實現(xiàn)方法
本篇文章是對在C語言中解決不用+、-、×、÷數(shù)字運算符做加法的方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05自己實現(xiàn)strcpy函數(shù)的實現(xiàn)方法
本篇文章介紹了,自己實現(xiàn)strcpy函數(shù)的實現(xiàn)方法。需要的朋友參考下2013-05-05OnSize、OnSizing和OnGetMinMaxInfo區(qū)別分析
這篇文章主要介紹了OnSize、OnSizing和OnGetMinMaxInfo區(qū)別分析,需要的朋友可以參考下2015-01-01基于C++執(zhí)行內(nèi)存memcpy效率測試的分析
本篇文章對C++中執(zhí)行內(nèi)存memcpy的效率進行了分析測試。需要的朋友參考下2013-05-05數(shù)據(jù)結構課程設計- 解析最少換車次數(shù)的問題詳解
數(shù)據(jù)結構課程設計- 解析最少換車次數(shù)的問題詳解2013-05-05