I'm reading Herb Sutter's book Exceptional C++, and in the second item you need to write a case insensitive string class ci_string with the following behavior:
#include <assert.h>
ci_string s("AbCdE");
// case insensitive
//
assert(s == "abcde");
assert(s == "ABCDE");
// still case-preserving, of course
//
assert(strcmp(s.c_str(), "AbCdE") == 0);
assert(strcmp(s.c_str(), "abcde") != 0);
My idea was to make this class the same as std::string
, and only to overwrite operator==
:
#include <string>
#include <cctype>
using namespace std;
struct ci_string : string {
bool operator==(const ci_string& lhs) {
if (this->length() != lhs.length())
return false;
for (size_type i = 0; i != this->length(); ++i) {
if (tolower((*this)[i]) != tolower(lhs[i]))
return false;
}
return true;
}
};
but, this code doesn't compile if you combine it with the first one, because there is no appropriate constructor of ci_string
for const char[]
as "AbCdE", although the parent class has one.
What is the most elegant way to solve this? I want the code to be as short as possible, without the need to rewrite string's constructors and member functions like c_str()
etc.