大文字と小文字を区別しない文字列を考え出そうとしていますが、Webで次の文字列を見つけました
http://www.gotw.ca/gotw/029.htm
したがって、基本的に、大文字と小文字を区別しない文字列を作成するためのコードは次のとおりです。
struct ci_char_traits : public std::char_traits<char> {
static bool eq( char c1, char c2 )
{ return toupper(c1) == toupper(c2); }
static bool ne( char c1, char c2 )
{ return toupper(c1) != toupper(c2); }
static bool lt( char c1, char c2 )
{ return toupper(c1) < toupper(c2); }
static int compare(const char* s1, const char* s2, size_t n )
{ return memicmp( s1, s2, n ); }
private:
static int memicmp(const void *s1, const void *s2, size_t n) {
if (n != 0) {
const unsigned char *p1 = (const unsigned char *)s1, *p2 = (const unsigned char *)s2;
do {
if (toupper(*p1) != toupper(*p2))
return (*p1 - *p2);
p1++;
p2++;
} while (--n != 0);
}
return 0;
}
};
// case insensitive string type definition
typedef std::basic_string<char, ci_char_traits> ci_string;
// provide standard output for case insensitive string
template<typename char_type, typename traits_type, typename allocator_type>
inline std::basic_ostream<char_type, traits_type>&
operator<<(std::basic_ostream<char_type, traits_type>& os,
const std::basic_string<char_type, ci_char_traits, allocator_type>& str) {
return std::__ostream_insert(os, str.data(), str.size());
}
したがって、型の定義は文字列です。今私が抱えている問題は、通常の文字列で機能するため、このカスタム文字列で機能する関数を取得できないことです。次のテンプレート関数は文字列から値を取得しますが、
template <typename T, class string_type, typename counter_type>
T stream_cast(const string_type& s) {
typedef typename string_type::value_type char_type;
typedef typename string_type::traits_type traits_type;
typename std::basic_istringstream<char_type, traits_type> iss(s);
T x;
char c;
if (!(iss >> x) || iss.get(c))
cout<<"*** ERROR *** Bad Conversion!"<<endl;
return x;
}
この関数を呼び出して、次のように文字列からdoubleを取得します。
ci_string str("2.0");
double test = stream_cast<double>(str);
しかし、演算子によるストリームオブジェクトの評価のため、大文字と小文字を区別しない文字列の定義に問題があります。常に失敗します(行!(iss >> x)は、この文字列型では常にtrueです)。
なぜ私がこの問題を抱えているのか誰かが知っていますか?この長い投稿をお読みいただき、ありがとうございます。
aa