I have a Matrix class template as follows:
template
class Matrix
{
T data[nrows][ncols];
public:
Just add a partial specialization:
template
class Matrix
{
T data[N][N];
public:
T& operator ()(std::size_t i, std::size_t j)
{
return data[i][j];
}
void setidentity(/*whatever params*/) { std::cout << "yay!"; }
};
Live Example
For general N * M
matrices, the general template will be instantiated, whereas only for N * N
matrics, this specialization is a better match.
Disadvantage: code repetition of all regular code. Could use a base class, but it's actually easier to do some SFINAE magic (below)
You can also use SFINAE by adding hidden template parameters N
and M
that default to nrows
and ncols
to setidentity
, and to enable_if
on the condition N == M
.
template
class Matrix
{
T data[nrows][ncols];
public:
T& operator ()(std::size_t i, std::size_t j)
{
return data[i][j];
}
template * = nullptr>
void setidentity(/*whatever params*/) {
static_assert(N == nrows && M == ncols, "invalid");
std::cout << "yay!";
}
};
Or, since the question was tagged C++11, use typename std::enable_if<(N == M)>::type
instead.
Live Example