space_voyager - 10 months ago 46

C++ Question

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 , print matrix using
`int`

`printf("%d ",matrix[i][j])`

- If the matrix type if or
`float`

, print matrix using`double`

`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>`

`error: wrong number of template arguments (2, should be 1)`

`print()`

`float`

`double`

Answer Source

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);
}
```