FiguringLife
FiguringLife

Reputation: 83

C++ Templates and comparing different types

I am trying to write a generic sort function in C++ using templates, but I am stuck in writing the greater function which returns true if lhs > rhs

template <typename T>
bool Sorter<T>::greater(T lhs, T rhs)
{
    return lhs > rhs;
}

The above code will take care of simple types such as int, long. What should I do so that the code works for std::string, std::string&, const char *. A code sample will be a great help.

Upvotes: 1

Views: 4786

Answers (3)

Gaminic
Gaminic

Reputation: 581

All those types come with comparison operators. Remember that char is just a 1byte number. For string, lexicographic order is used.

String comparison

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258678

You'll have to specialize the template for types where the comparison isn't as straight-forward as saying lgs>rhs.

Here's how I'd re-write your code:

template <typename T>
bool greater(T const& lhs, T const& rhs)
{
    return lhs > rhs;
}

and here's how you'd specialize it:

template<>
bool greater<string>(string const& lhs, string const& rhs)
{
     //
}    

membership removed for simplicity.

Note that there already is a std::greater.

Upvotes: 4

Nim
Nim

Reputation: 33655

I'd say the only one you'd have to worry about is const char*, std::string should already have operator> defined somewhere... (normally in <string>)

For const char*, provide a specialization.. e.g..

template <>
bool Sorter<const char*>::greater(const char* lhs, const char* rhs)
{
  return std::strcmp(lhs, hs) > 0;
}

Upvotes: 7

Related Questions