I was learning the std::char_traits used in c++ string, then I realized that std::char_traits could be used to create customized string classes, like case_insensitive_string as in the cplusplus.com's article, I will paste the code sample below.
// char_traits::compare
#include <iostream> // std::cout
#include <string> // std::basic_string, std::char_traits
#include <cctype> // std::tolower
#include <cstddef> // std::size_t
// case-insensitive traits:
struct custom_traits: std::char_traits<char> {
static bool eq (char c, char d) { return std::tolower(c)==std::tolower(d); }
static bool lt (char c, char d) { return std::tolower(c)<std::tolower(d); }
static int compare (const char* p, const char* q, std::size_t n) {
while (n--) {if (!eq(*p,*q)) return lt(*p,*q); ++p; ++q;}
return 0;
}
};
int main ()
{
std::basic_string<char,custom_traits> foo,bar;
foo = "Test";
bar = "test";
if (foo==bar) std::cout << "foo and bar are equal\n";
return 0;
}
As far as I know, static methods are part of the class, not instances. So we cannot override the static methods. The custom_trais class, however, explicitly inherits the char_trais class. Does anybody know how this works? Thanks.