简体   繁体   中英

template function auto return type with std::conditional

I would like to write a generic function that could take either

(1) a rvalue reference of A and return a move-constructed type B:

A a;
B b = f(std::move(A));
// use b normally and a is now empty.

or (2) a lvalue reference of A and return a wrapper object that wraps A from automatic type deduction:

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. 

I am able to do this by doing the following:

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. 
 }

My question is, as pointed out in the comments of the code above, how to remove that repeating of computation in the decltype() call without using decltype(auto) as auto keyword is prohibited in template parameter of std::conditional ?

Thank you in advance!

There is no repeating computation, just code duplication. Code duplication can be avoided using a function.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM