Yuriy Lisovskiy
Yuriy Lisovskiy

Reputation: 521

Template function that can compare different data types c++

I need to write a template function that can compare integers, chars and strings, but there is a condition: strings must be compared by their lenghts.

I have some code:

template<typename data>
bool compare(data left, data right)
{
    if (typeid(left) == typeid(string))
    {
        return strlen((char*)left) > strlen((char*)right) ? true : false;
    }
    return left > right ? true : false;
}

When I compare two strings, there is an error in line 6: C2440 'type cast': cannot convert from 'std::string' to 'char*'

I tried another way, I replaced line 6 with return left.length() > right.lenght() ? true : false;, but if I compare non-string data, I have an error: C2228 left of '.length' must have class/struct/union

So, how can I implement this function correctly ?

Upvotes: 2

Views: 2583

Answers (1)

wally
wally

Reputation: 11032

You could specialize the template for string:

template<typename data>
bool compare(data left, data right)
{
    return left > right;
}

template<>
bool compare(std::string left, std::string right)
{
    return left.length() > right.length();
}

Also the ternary operator is not required. Rather than return left > right ? true : false; you could just return left > right;

Also, watch out for character literals decaying into pointers: compare("Hi", "There"); would compare the pointer addresses. So the following is probably also required:

template<>
bool compare(const char* left, const char* right)
{
    return std::strlen(left) > std::strlen(right);
}

Upvotes: 4

Related Questions