From e23d6a9be05271406829cc4724753339472bf758 Mon Sep 17 00:00:00 2001 From: Florian Fleissner Date: Fri, 20 Sep 2019 09:30:21 +0200 Subject: [PATCH] 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 --- src/kaleidoscope/MatrixAddr.h | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/kaleidoscope/MatrixAddr.h b/src/kaleidoscope/MatrixAddr.h index b1a1872b..cd47ab2f 100644 --- a/src/kaleidoscope/MatrixAddr.h +++ b/src/kaleidoscope/MatrixAddr.h @@ -66,8 +66,15 @@ class MatrixAddr { ThisType &operator=(ThisType &&) = default; template + 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;