Martin - 1 year ago 89

C++ Question

I want to define conversion to float for matrix<1, 1>. I have trouble figuring out how to actually define it. If I make it a global function

`template<typename T>`

inline operator T(const matrix<T, 1, 1> &m){ return m(0, 0); }

I get "operator.. must be a non static member function"

I can of course define it as member for the generic matrix template but then it will be defined for all matrices - which is not what I want. I want it to be defined only for the specific case of 1x1 matrix.

Answer Source

You have to specialize a class for that, for example:

```
template <typename Base, typename T, std::size_t W, std::size_t H>
struct MatrixConversion
{ /*Empty*/ };
template <typename Base, typename T> struct MatrixConversion<T, 1u, 1u>
{
operator const T&() const { return static_cast<const Base&>(*this).m[0][0]; }
};
template <typename T, std::size_t W, std::size_t H>
struct Matrix : MatrixConversion<Matrix<T, W, H>, T, W, H>
{
// Your code
};
```