How to use template to specialize a function with char *?

Asked

Viewed 159 times

0

I am doing C++ exercises and created a template for the function of returning the highest value.

template<class Type>
Type maximo (const Type a, const Type b) {
    if (a > b) {
        return a;
    }
    return b;

Now the list of exercises asks me to specialize the function to work with the char type *, and gives the following template:

template <>
Tipo funcao<Tipo>(Tipo param1, Tipo param2, ...) { ... }

Type is the concrete type to be used in specialization ( int , double , char * etc.).

Step 6: (Challenge 1) Specialize the maximum function() to handle char * using the above syntax. Use the strcmp() function; you need to include cstring. Make modifications to main() to test these functions. Compile and test next.

But I can’t make it turn. My function was:

template <>
char * maximo<char *>(const char *a, const char *b) {
    if (strcmp(a ,b) < 0) {
        return a;
    }
    return b;
}

1 answer

1


Note that in the template statement, you did:

template<class Type>
Type maximo (const Type a, const Type b);

and now wants to specialize to char *. Then you must replace Type for char *, that is to say

template <>
char * maximo(char *a, char *b);

Note that you do not have the const. If you want to replace it with const char *, has to stay:

template <>
const char * maximo(const char *a, const char *b);

that is, the type of return has to be const char *

Browser other questions tagged

You are not signed in. Login or sign up in order to post.