Eisa Eisa - 25 days ago 7
C++ Question

How to define a function that can work on both int and long int for one of its variables in C/C++?

Lets say that I have a very simple print matrix function like:

void print_mat_N_1(int rows, int *matrix) {
for (int r = 0; r < rows; ++r) {
cout << matrix[r];
cout << endl;
}
cout << endl;
}


This function can work on my
int *C
one dimensional matrix(lets think I allocated it correctly to be a one dimensional matrix of lets say length 4, just don't argue that its a pointer and not a matrix I'm aware of that) perfectly and will print the results.

The point is that it cant work on
long int *C
by definition and as expected.
My solution was(which is working) to duplicate the function with the same name like:

void print_mat_N_1(int rows, long int *matrix) {
for (int r = 0; r < rows; ++r) {
cout << matrix[r];
cout << endl;
}
cout << endl;
}


Is this the only and best fix or not? I want to have the same name for different variably types, lets say float, double, unsigned,etc.

Well this "want" can also be argued, is it a bad idea to have this function that can work on different types on the same name? should I just define them with different names?

Answer

Use a function template and static_assert the type so that an user can't pick a wrong type up:

template<typename T>
void print_mat_N_1(int rows, T *matrix) {
    static_assert(std::is_same<T, int>::value or std::is_same<T, long int>::value, "!");

    for (int r = 0; r < rows; ++r) {
        cout << matrix[r];
        cout << endl;
    }

    cout << endl;
}

You can do something similar with std::enable_if if you prefer:

template<typename T>
std::enable_if_t<std::is_same<T, int>::value or std::is_same<T, long int>::value>
print_mat_N_1(int rows, T *matrix) {
    for (int r = 0; r < rows; ++r) {
        cout << matrix[r];
        cout << endl;
    }

    cout << endl;
}
Comments