c++ - 使用 <charT> 比较单个字符

标签 c++ templates

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

template <class charT>
class CQuickJson final
...
size_t CQuickJson::ParseStringArray(charT *jsonData, size_t pos)
{
    while (jsonData[pos] != L'\0')
    {
    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("test\f");
   std::cout << std::endl;
   test(L"test\f");
   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';
  /// ..
};

关于c++ - 使用 <charT> 比较单个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21703107/

相关文章:

javascript - 在 angularJS 1.x 中呈现 HTML

c++ - 在我的 friend 圈中找到最受欢迎的点赞

c++ - 如何在 C++ 中创建和使用非类型模板以及将在何处使用

c++ - 我应该让我的功能尽可能通用吗?

c++ - 有没有什么类或者结构可以让C++中的矩阵运算更加得心应手?

json - Azure APIM-无法访问液体模板中的 json 正文值

javascript - Knockout 3.2.0 - 在模板内传递额外参数

C++ Ranges TS 包括实验路径

c++ - Visual C++ 数组大小崩溃

c++ - STL 友好的 pImpl 类?