我有一个看起来像这样的模板类:
template <typename T, std::size_t M, std::size_t N> // MxN matrix with elements of type T
struct Mtx{...}
// component wise division
template <typename U> Mtx operator/(const Mtx<U, M, N> &rhs) const
{ return componentDivide(*this, rhs); }
确保类似函数的返回类型operator /
为“正确”的最佳方法是什么?
例如:
Mtx<float> * Mtx<unsigned> = Mtx<float>
Mtx<float> * Mtx<int> = Mtx<float>
Mtx<float> * Mtx<double> = Mtx<double>
Mtx<double> * Mtx<float> = Mtx<double>
Mtx<short> * Mtx<int> = Mtx<int>
我个人倾向于decltype(std::declval<T>() / std::declval<U>())
而不是std::common_type
,因为它明确选择类型以反映实际的划分。
从而:
template <typename T>
struct Mtx
{
T _var;
template <typename U>
Mtx<decltype(std::declval<T>() / std::declval<U>())>
operator / (const Mtx<U> &rhs) const
{
return this->_var / rhs._var;
}
};
或者,通过使用尾随返回类型,以便我们可以用参数的类型来表示它:
template <typename T>
struct Mtx
{
T _var;
template <typename U>
auto operator / (const Mtx<U> &rhs) const
-> Mtx<decltype(this->_var / rhs._var)>
{
return this->_var / rhs._var;
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句