Different constructor in template: one for string and one for anything else

63 views Asked by At
#include <iostream>
#include <string>
using namespace std;

template <class Type>
class Matrix
{
public:
    Type matrix[2][2];

        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                if (typeid(matrix[0][0]).name() == typeid(string).name()) {
                    matrix[i][j] = "0";
                }
                else {
                    matrix[i][j] = 0;     //this is where I get C2593
                }
            }
        }
    }
};

int main()
{
    Matrix<string> mString;
    Matrix<int> mInt;
    .
    .
    .
    return 0;
}

So, I'm having this matrix template and I want to initialize it with "0" if the type of the matrix is string. Else, I want to initialize with 0. I tried this thing here and I get an error C2593: 'operator =' is ambiguous. Is there anything I can do, or my approach is totally wrong?

1

There are 1 answers

1
Barry On BEST ANSWER

It ultimately depends on how much of Matrix differs between int and string.

If all you're dealing with is the initial default value, the simplest solution is probably to outsource to a helper function:

template <class Type>
class Matrix
{
    Matrix() {
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                setDefault(matrix[i][j]);
            }
        }
    }

    // ...

    template <typename U>
    void setDefault(U& u) { u = 0; }

    void setDefault(std::string& u) { u = "0"; }
};

If you're doing something more complicated, then you probably want to explicitly specialize:

template <>
class Matrix<std::string> {
    // Matrix of strings
};