C++ C++;14 Can运算符*=是否为constexpr?(矩阵类)
我有以下矩阵类:C++ C++;14 Can运算符*=是否为constexpr?(矩阵类),c++,operator-overloading,c++14,constexpr,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) noex
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*=
实现为constepr
函数。以下是我的实现:
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;
}
constexpr mat4&mat4::operator*=(const mat4&other)无异常
{
std::array tmp;//由于乘法依赖于矩阵*this和other,因此临时值是必需的。
//矩阵乘法(三个嵌套循环用于填充tmp)
交换(这个->矩阵,tmp);//有什么特别的原因需要交换这两个数组吗?也就是说,为什么不在constepr函数中使用matrix=tmp;
这一点很好呢?当然,很多std::array
成员函数在C++17之前都不是constepr,所以你可能会因此而遇到麻烦。@melak47告诉我是否错了,但我的第一个想法是这样的matrix=tmp;
执行一个复制操作,而std::swap
执行一个移动操作(更快)。但即使使用前者,我还是通过叮当声得到了这个输出:error:constexpr函数从不生成常量表达式[-Winvalid constexpr]1>constexpr mat4&mat4::operator*=(const mat4&other)noexcept
无法复制:C++17之前的std::array
与constexpr
混合不好。请使用本机数组或编写自己的constexpr
-ifiedarray
。
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;
}