Force explicit type conversion for MatrixAddr

By forcing an explicit type conversion between
two template class instances of template
MatrixAddr<...>, we prevent undesired implicit
construction of the wrong MatrixAddr type.

Before this change, the following would have been possible

typedef MatrixAddr<5, 5> KeyAddr;

void f(KeyAddr k) {} // uses MatrixAddr<5, 5>

void g() {
   typedef MatrixAddr<0, 0> KeyAddr; // Stupid but possible
   f(KeyAddr(1, 12)); // Would instantiate MatrixAddr<0, 0> and
                      // implicitly convert it to MatrixAddr<5, 5>
}

With this commit, the compiler will emit an error and explicit type
conversion is required.

typedef MatrixAddr<5, 5> KeyAddr1;
typedef MatrixAddr<2, 2> KeyAddr2;

void f(KeyAddr1 k) {} // uses MatrixAddr<5, 5>

void g() {
   f(KeyAddr1(KeyAddr2(1, 1)); // Now an explicit type conversion is
                               // required.
}

This commit also introduces a compile time check that prevents
conversion from a matrix type with greater extension to one with
smaller extension.

Signed-off-by: Florian Fleissner <florian.fleissner@inpartik.de>
pull/689/head
Florian Fleissner 5 years ago
parent f8fa47610b
commit e23d6a9be0

@ -66,8 +66,15 @@ class MatrixAddr {
ThisType &operator=(ThisType &&) = default;
template<typename MatrixAddr__>
explicit
constexpr MatrixAddr(const MatrixAddr__ &other)
: MatrixAddr(other.row(), other.col()) {}
: MatrixAddr(other.row(), other.col())
{
static_assert(MatrixAddr__::rows <= ThisType::rows,
"Matrix type conversion failed. Source type must not have greater row size than target type");
static_assert(MatrixAddr__::cols <= ThisType::cols,
"Matrix type conversion failed. Source type must not have greater col size than target type");
}
constexpr uint8_t row() const {
return offset_ / cols;

Loading…
Cancel
Save