将单个字符与<charT>

Comparing single characters with <charT>

本文关键字:charT gt 单个 lt 字符      更新时间:2023-10-16

我正在转换我的 JSON 解析器以支持 wchar_tchar .我可以为此使用charT(性格特征类)吗?如果是这样,那么我该如何比较单个字符,目前我的代码是这样的:

template <class charT>
class CQuickJson final
...
size_t CQuickJson::ParseStringArray(charT *jsonData, size_t pos)
{
    while (jsonData[pos] != L'')
    {
    switch (jsonData[pos])
    {
            case L' ':
            case L'f':
            case L'n':
            case L'r':
            case L't':
            case L'v':
            case L',':
                // Ignore whitespace characters and commas
                break;
            // ...
    }
}

如您所见,我尝试检查某些宽字符,但我也想检查相同的 ASCII 字符,即。 L'f ' 也应该检查'f' - 我猜这里需要static_cast<>或其他东西,但我还没有卡住。

不确定

这是否是你所追求的,但你可以创建特质类:

#include <iostream>
#include <string>
template <class charT>
  struct js_traits { };
template <> struct js_traits<char> {
  static constexpr char txt_f() { return 'f'; }
  /// ..
};
template <> struct js_traits<wchar_t> {
  static constexpr wchar_t txt_f() { return L'f'; }
  /// ..
};
template<class wcharT>
void test(const wcharT* s) {
    while(*s) {
     switch (*s) {
       case js_traits<wcharT>::txt_f():
       std::cout << "<f>";
       break;
       default:
       std::cout << *s;
     };       
     s++;
    } 
}
int main()
{
   test("testf");
   std::cout << std::endl;
   test(L"testf");
   std::cout << std::endl;
}

输出:

test<f>    
116101115116<f>

使用 G++4.8 进行测试http://coliru.stacked-crooked.com/a/4b9e3b5f22eafcc0

或者如果不允许constexpr

template <class charT>
  struct js_traits { };
template <> struct js_traits<char> {
  static const char txt_f = 'f';
  /// ..
};
template <> struct js_traits<wchar_t> {
  static const wchar_t txt_f = L'f';
  /// ..
};

使用 std::ctype<charT>::narrow

auto &loc = std::locale::classic();
assert(std::use_facet<std::ctype<wchar_t>>(loc).narrow(L' ', 0) == ' ');
assert(std::use_facet<std::ctype<char>>(loc).narrow(' ', 0) == ' ');

请注意,即使在charT char的情况下,您也可以在模板化代码中使用它,因为std::ctype<char>::narrow是无操作的。

可能最好的办法是使用 std::string :这避免了裸指针的所有混乱,并支持charwchar_t 毕竟,您正在处理 json 字符串,而不是带有字符的以零结尾的缓冲区。

template<typename T>
size_t CQuickJson::parseString(const std::basic_string<T>& jsonData, size_t pos) 
{
   auto current = jsonData.begin();
   std::advance(current, pos);
   switch( *current ) {
     ...
   }
}