将单个字符与<charT>
Comparing single characters with <charT>
我正在转换我的 JSON 解析器以支持 wchar_t
和 char
.我可以为此使用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
:这避免了裸指针的所有混乱,并支持char
和wchar_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 ) {
...
}
}
相关文章:
- EASTL矢量<向量<int>>连续的
- 如何将 std::ifstream 转换为 std::basic_istream<CharT, Traits>&?
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- C 字符串比较“祝您好运”&gt;“再见”
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- C 操作员&gt;&gt;与突变器过载
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 是否需要使用 - &gt;运算符在C 中调用成员函数时
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- 错误c++visual studio c2227左侧'->;Init';必须指向类/结构/联合/泛型类型
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- ``这个''不能用this-&gt;指针变量
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 使用shared_ptr<字符串>转换为一个无序集合<字符串>
- 将单个字符与<charT>