If you need to have the comparison operators work in a template for C-style strings (null terminated arrays of char
), you will have to have a specialized template along with your generic template. The thorn is that C-style strings cannot be compared using the operators.
template <class t>
int compare(const char * a, const char * b)
{
return strcmp(a, b);
}
template <class t>
int compare(const t& a, const t& b)
{
return (a == b) ? 0 : ((a < b) ? -1 : 1);
}
Note: This templated function will fail for all classes that do not have operator<
or operator==
defined. Which will cause havoc down the road. This looks very much like a using C++ templates to force things into the C language methodology.
A Better Approach
I see two C++ specific features that could make your life easier: Overloading operators and using std::string
. Using these features will eliminate your need for the templated functions.
Overloading Operators
One reason for having a templated compare function is because the class doesn't have comparison operators devined (otherwise you would use the operators). So, define the overloaded operators <
and ==
. The other operators >, >=, <=
and !=
can be defined in terms of the latter two. See boost
operators header.
Using std::string
The problem of using comparison operators on C-style strings can be removed by replacing them with std::string
. A nice feature of std::string
is that it has the comparison operators already defined. Thus you can use <
to compare two std::string
objects.
Summary
Rather than creating a template function that uses C-style comparing (e.g. return -1, 0, or +1), define comparison operators for your classes and convert null terminated arrays of characters into instances of std::string
.