有条件地重载操作符

Conditionally overload an operator

本文关键字:操作符 重载 有条件      更新时间:2023-10-16

我目前正在实现一些数学基础操作,并尽可能避免使用第三方库。由于Scalar*VectorVector*Scalar的乘法,我被困在了operator*的过载上。Scalar*Vector点积的当前代码:

#include <vector>
#include <type_traits>
template<class Vector, class Scalar>
typename std::enable_if<std::is_floating_point<Scalar>::value, Vector>::type operator*
(
    const Scalar &a,
    const Vector &b
)
{
    return Vector
            (
                a*b[0],
                a*b[1],
                a*b[2]
            );
}
int main()
{
    const std::vector<double> v1({1,2,3});
    const double s1(2);
    const auto result(s1*v1);
    std::cout<< result << std::endl;
}

编译器错误信息为:

error: invalid operands to binary expression ('double' and 'const std::vector')

关于如何重载*运算符,以便两个点积都是可能的,有什么建议吗?我不打算在自定义vector类中实现这两个操作符,就像重载操作符一样。而不是那样,我的目标是模板化操作符。

我在这里找到了一个很好的解释,并用它来调整向量操作。在vector类头文件中,基本上可以通过struct is_vector定义任何类型的T在默认情况下都不是vector。在下面的a中,必须显式列出可以作为向量的所有类型,例如std::vector

#include <vector>
#include <type_traits>
template <typename T>
struct is_vector
{
    static const bool value = false;
};
template <>
struct is_vector< std::vector >
{
    static const bool value = true;
};
template <class Vector>
typename std::enable_if<std::is_vector<Vector>::value, double>::type
operator*(const Vector &a, const Vector &b);

在可执行文件中,代码看起来是一样的。

int main()
{
    const std::vector<double> v1({1,2,3});
    const double s1(2);
    const auto result(s1*v1);
    std::cout<< result << std::endl;
}