I need to do something like this:
template <typename Matrix_xx>
bool ProcessMatrix<Matrix_xx>::function1(Matrix_xx a) {
int x, y;
// ... some code here ... //
if (Matrix_xx == Matrix_1D) {
a->readFromFile(x);
} else if (Matrix_xx == Matrix_2D) {
a->readFromFile(x, y);
} // ...
}
i.e., to call different functions depends on the template argument. The code above wouldn’t compile because there are only Matrix_1D::readFromFile(int x) and Matrix_2D::readFromFile(int x, int y). I don’t want to split function1 into two different functions only because there would be a lot of doubled code. Is there another way?
Wrap the type-specific code in either overloaded function or explicitly specialized template:
If
Matrix_xxisMatrix_1D, overloading will select the first overload, if it is Matrix_2D, overloading will select the second overload and if it’s anything else, it won’t compile. But if somebody provides new type of matrix, they can make it compile by defining thedoReadFromFilefor it.This is generally useful trick and reason why standard library uses “traits”—they can be defined for class somebody gives you and they can be defined for non-class types. The “traits” can be either in the form of explicitly specialized templates or free functions, usually looked up with argument-dependent lookup (placed in the namespace of their argument, not the template).
For completeness, the explicit specialization would look like: