C ++ 14运算符* =是constexpr吗? (矩阵类)

时间:2016-08-02 15:09:10

标签: c++ operator-overloading c++14 constexpr

我有以下矩阵类:

class mat4
{
public:
    constexpr mat4() noexcept;

    constexpr mat4(const std::array<float, 16> &m) noexcept;
    constexpr mat4(std::array<float, 16> &&m) noexcept;

    constexpr mat4(const mat4 &other) noexcept;
    constexpr mat4(mat4 &&other) noexcept;

    /*constexpr?*/ mat4& operator*=(const mat4 &other) noexcept;

    mat4& operator=(mat4 other) noexcept; // Uses std::swap

    constexpr float& operator[](size_t index);
    constexpr float operator[](size_t index) const;

private:
    std::array<float, 16> matrix;
};

constexpr const mat4 operator*(mat4 lhs, const mat4 &rhs) noexcept;

我希望对operator*实施operator*=,就像通常使用operator+operator+=一样。第一个参数是通过值传递给复制省略

constexpr const mat4 operator*(mat4 lhs, const mat4 &rhs) noexcept
{
    lhs *= rhs;
    return lhs;
}

但是,我认为无法将operator*=实现为constexpr功能。这是我的实施:

constexpr mat4& mat4::operator*=(const mat4 &other) noexcept
{
    std::array<float, 16> tmp; // The temporary is mandatory because the multiplication depends on the matrices *this and other.

    //matrix multiplication (three nested for loop to fill tmp)

    std::swap(this->matrix, tmp); // <-- ERROR: NOT CONSTEXPR
    return *this;
}

我想到的另一种方法是根据operator*=定义operator*,并在前者的主体中写出类似*this = *this * other的内容。但是,它会调用operator=而不是constexpr,因为它还会在其身体中调用std::swap

有没有办法让operator+=成为constexpr函数?

0 个答案:

没有答案