我正在转换我的 JSON 解析器以支持 wchar_t
和 char
.我可以使用 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/