space_voyager space_voyager - 1 month ago 9
C++ Question

Member specialization for a templated class for groups of types?

I have a matrix class and I want to print the matrix to the terminal differently for different matrix types (int, float, double). I want to achieve this:


  • If the matrix type if
    int
    , print matrix using
    printf("%d ",matrix[i][j])

  • If the matrix type if
    float
    or
    double
    , print matrix using
    printf("%.3f ",matrix[i][j])

  • Otherwise, throw an error



Here are the relevant parts of what I have:

...

template <class T>
class Matrix2D {
private:
std::vector< std::vector<T> > matrix;
public:
...
void print() const; // print the whole matrix
}

...

template <class T>
void Matrix2D<T>::print() const {
// throw an error
}

template <>
void Matrix2D<int>::print() const {
// print matrix using printf("%d ",matrix[i][j])
}

template <>
void Matrix2D<float,double>::print() const {
// print matrix using printf("%.3f ",matrix[i][j])
}


But using
Matrix2D<float,double>
gives me the error message
error: wrong number of template arguments (2, should be 1)
. I want, however, to have a common
print()
function for both
float
and
double
type matrices (don't want to copy the same thing twice). What is the simplest way to achieve this? Thanks!

Answer

just as an alternative to proposed templated solutions, using old good function overloading:

public:
    void print() const
    {
        for (auto const& row : matrix)
            for (auto const& v : row)
                print(v);
    }

private:
    static void print(int val)
    {
        printf("%d ", val);
    }

    static void print(float val)
    {
        printf("%.3f", val);
    }