具有std :: conditional的模板函数自动返回类型

时间:2018-12-07 03:29:12

标签: c++ templates generic-programming rvalue-reference

我想编写一个通用函数,可以采用其中任何一个

(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()调用中不使用decltype(auto)作为auto关键字来消除重复的计算模板参数std::conditional

提前谢谢!

1 个答案:

答案 0 :(得分:1)

没有重复计算,只有代码重复。使用函数可以避免代码重复。

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