繁体   English   中英

推导返回值的类型

[英]Deducing the type of a return value

作为一个精简到最低限度的例子,我们有容器:

template<class T> class container{
public: 
  T t[3];
};

我想对这些结合了T各种值的容器进行操作。 例如,将实数容器添加到复数容器中。 这是通过声明运算符来完成的:

 inline container<std::complex<double>> operator+(const container<double>& A, const container<std::complex<double>>& B){
  container<std::complex<double>> sum;
  for(int i=0; i<3; ++i){
    sum.t[i]=A.t[i]+B.t[i];
  }
  return sum;
}

inline container<std::complex<double>> operator+(const container<std::complex<double>>& A, const container<double>& B){
  return B+A; 
}

我不能使用auto因为我处理的是容器而不是元素。

这工作正常,只是它会导致代码重复。 在一个真实的例子中,有更多的操作员,我可以拥有容器的容器。

有没有更好的方法来做到这一点?

我曾尝试使用std::conditionalstd:::is_same但这似乎不起作用。

非常感谢!

怎么样(未经测试):

template <class LhsElem, class RhsElem>
inline auto operator+(const container<LhsElem>& A, const container<RhsElem>& B){

  // Probe what the result type will be
  using ResultType = decltype(std::declval<LhsElem const&>() + std::declval<RhsElem const&>());

  container<ResultType > sum;
  for(int i=0; i<3; ++i){
    sum.t[i]=A.t[i]+B.t[i];
  }
  return sum;
}

这就是我想要做的。 我面临的问题是我不知道我必须在std::is_same<...>表达式的末尾添加::value所以它不起作用,我开始认为这是不可能的。

template<class T1, class T2> inline auto operator+(const container<T1>& A, 
                                                   const container<T2>& B){
  std::conditional<std::is_same<T1, std::complex<double>>::value 
                   || std::is_same<T2, std::complex<double>>::value,   
                   container<std::complex<double>>, container<double>> sum;
  for(int i=0; i<3; ++i){
    sum.t[i]=A.t[i]+B.t[i];
  }
  return sum;  
}

暂无
暂无

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

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