Chi*_*iru 2 c++ templates types return matrix
我用Matrix这种方式声明了一个模板类:
template<typename Type> class Matrix {
// Some code for matrix computations
}
Run Code Online (Sandbox Code Playgroud)
现在,我试图以operator+一种方式重载,以保证更大的Type将成为结果.我在尝试这件事:
template<typename OtherType>
Matrix<Type> operator+ (Matrix<OtherType> mat) {
// Dimension check and matrix addition code
}
Run Code Online (Sandbox Code Playgroud)
但这样做,我几乎会迫使C++选择Matrix<Type>作为返回类型.我想要实现的是,例如,Matrix<int>+ Matrix<float>将导致Matrix<float>.
有关如何做到这一点的任何建议?
您可以使用编译时条件:
template<
typename OtherType,
typename T = typename std::conditional<(sizeof(Type) <= sizeof(OtherType)),
OtherType, Type>::type
>
Matrix<T> operator+ (const Matrix<OtherType>& mat);
Run Code Online (Sandbox Code Playgroud)
或使用C++ 11功能decltype推断出类型:
template<typename OtherType>
auto operator+ (const Matrix<OtherType>& mat)
-> Matrix<decltype(std::declval<OtherType>() + std::declval<Type>())>;
Run Code Online (Sandbox Code Playgroud)