The code you've listed will not compile, since you're essentially trying to implement a T
constructor outside the definition of T
; or if it's a fundamental type, or an array, it makes even less sense.
What you can do instead is implement a casting operator within your matrix class - by either adding it to the general template or specializing matrix
for M=1 and N=1.
The first option would look like this:
template<int M, int N, typename T=double>
class matrix{
// ...
operator T() const {
static_assert(M == 1 and N==1,
"Attempting to treat a matrix with multiple cells as a scalar");
// code to return the single matrix element
}
}
and the second:
template<int M, int N, typename T=double>
class matrix{
// ...
}
template<typename T=double>
class matrix<1, 1, T>{
// ... some code duplication here with the main template; or maybe
// actually have different implementation banking on the fact that
// it's really just a scalar.
operator T() const {
// code to return the single matrix element
}
}
but frankly, I don't think I'd recommend any of these options. I'd probably do one of the following:
- Alter function which takes a T so that it can "naturally" take 1x1 matrices (e.g. by templating)
- Alter function which takes a T so that it can "naturally" take any matrix. A lot of scalar work has interesting generalization to matrices.
- Be explicit about the conversion, perhaps writing a
template <typename T> T as_scalar(const matrix<1,1,T> m)
function.