两参数模板模糊二元运算符重载

问题描述

所以我有一个基于CRTP的矩阵类(派生类型),它需要两个模板参数template<class T,class Derived>,并且需要重载二进制运算符+-和{{1 }}乘以标量(T类)的矩阵。对于*运算符,例如它将是

*

然后,例如使用template <class T,class Derived> Derived operator*(const Derived &other,const T scalar) { Derived result = other; for (size_t i = 0 ; i < other.get_rows(); i++) { for (size_t j = 0; j < other.get_cols(); j++) { result(i,j) *= scalar; } } return result; } template <class T,class Derived> Derived operator*(const T scalar,const Derived &other) { return other * scalar; } ,其中a * A是双标量,而a是矩阵对象(动态),编译器将无法理解要使用哪个运算符,无论类类型,因为使用的模板(AT)含糊不清。

这里有人解决吗?我是否需要重载特定模板参数,例如Deriveddouble等??

解决方法

编译器可能无法识别两个重载,这两个重载都为参数采用任意类型。在

template <class T,class Derived>
Derived operator*(const Derived &other,const T scalar)  {...}

DerivedT只是可以用 any 类型替换的模板参数。其他操作员也是如此。两者都声明了一个operator*,适用于任何两种类型。

如果矩阵的类型为Derived(即某个地方有class Derived { ... };),则可能是要使用此类型,而不要使用具有相同名称的模板参数。

template <class T>
Derived operator*(const Derived &other,const T scalar) {...}

template <class T,class Derived>
Derived operator*(const T scalar,const Derived &other) {...} 

现在您有两个运算符,它们将Derived的实例作为lhs,将任何其他类型作为rhs,反之亦然。

此外,您可以使用std::enable_ifC++ 20 concepts & constraints模板通过std::is_integralstd::is_floating_point限制T的类型,以仅允许{{1} }就是数字。


或者,如果您不能或不想对不同的矩阵子类使用运行时多态性,则可以保留初始方法(带有两个模板参数),但限制T允许的类型使用std::is_same的上述方法。然后SFINAE应该选择正确的过载。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...