[英]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::conditional
和std:::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.