简体   繁体   English

模板函数自动返回类型与std :: conditional

[英]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: (1)A的右值引用并返回移动构造的类型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: 或(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. 

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 ? 我的问题是,正如上面代码的注释中所指出的,如何在不使用decltype(auto)作为auto关键字的情况下在decltype()调用中删除重复计算,这在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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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