[英]How to deduce the return type of a function template base on a “function like” parameter?
考慮以下功能模板:
template<typename A, typename B, typename Op>
B Apply(A a, Op f)
{
return f(a);
}
要使用它,必須顯式指定模板參數:
auto y = Apply<int, std::string>(2, [](int x){ return std::to_string(x); });
我想創建一個由編譯器推斷出參數的版本,這樣我就可以將其稱為auto y = Apply(...);
應用函子的基本c ++ 14食譜解決方案:
std::forward
生活中的一切。 decltype(auto)
我們可以用來將您的代碼示例浸入其中:
template<typename F, typename A>
decltype(auto) Apply(F&& f, A&& a) {
return std::forward<F>(f)(std::forward<A>(a));
}
為了增加調味料,我們還可以提供一個例外說明:
template<typename F, typename A>
decltype(auto) Apply(F&& f, A&& a)
noexcept(noexcept(std::forward<F>(f)(std::forward<A>(a)))) {
return std::forward<F>(f)(std::forward<A>(a));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.