[英]template function auto return type with std::conditional
我想編寫一個可以采用的通用函數
(1)A的右值引用並返回移動構造的類型B:
A a;
B b = f(std::move(A));
// use b normally and a is now empty.
或(2)A的左值引用並返回一個包裝自動類型扣除A的包裝器對象:
A a;
auto b = f(A);
// a could be used normally. The type of b is of a very complex form deduced based on the implementation of f()
B bb = b.eval(); // use eval() method from the auto type to make an evaluation of the wrapper object b to effectively copy-construct bb from a.
我可以通過執行以下操作來完成此操作:
template <typename T>
auto f(T&& t)
-> typename std::conditional
<!std::is_lvalue_reference<T>::value,
T,
decltype (t.sqrt() + (t * 2).sin()) // ideally this could be decltype(auto) to not repeat the code but this is not allowed by C++
>::type
{
T _t(std::forward<T>(t));
return _t.sqrt() + (_t * 2).sin() // T is a data type of some template expression library with lazy evaluation capability, e.g., Eigen::Matrix, hence this line will return an expression type that is composed from the types involved in the expression, i.e. sqrt, +, *, sin.
}
我的問題是,正如上面代碼的注釋中所指出的,如何在不使用decltype(auto)
作為auto
關鍵字的情況下在decltype()
調用中刪除重復計算,這在std::conditional
模板參數中是禁止的?
先感謝您!
沒有重復計算,只是代碼重復。 使用函數可以避免代碼重復。
template <typename T>
auto f(T&& t)
-> typename std::conditional
<!std::is_lvalue_reference<T>::value,
T,
decltype (function(t))
>::type
{
T _t(std::forward<T>(t));
return function(_t);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.