gpt4 book ai didi

c++ - Facet ctype、do_is() 和特化

转载 作者:行者123 更新时间:2023-11-28 06:58:22 24 4
gpt4 key购买 nike

我派生了 ctype 类来构建我自己的 facet,以便覆盖它的虚函数 do_is()。我的目的是让流提取器忽略空格字符(并且仍然对制表符进行标记)。这种重写调用了母类的实现。但它只会用 wchar_t 编译。 char 模板值没有ctype::do_is() 的实现。对于 gcc 和 VS 2010 也是如此。

这是我的代码;您只需取消注释第 5 行即可在两个版本之间进行测试。

#include <iostream>
#include <locale>
#include <sstream>

// #define WIDE_CHARACTERS

#ifdef WIDE_CHARACTERS
typedef wchar_t CharacterType;
std::basic_string<CharacterType> in = L"string1\tstring2 string3";
std::basic_ostream<CharacterType>& consoleOut = std::wcout;
#else
typedef char CharacterType;
std::basic_string<CharacterType> in = "string1\tstring2 string3";
std::basic_ostream<CharacterType>& consoleOut = std::cout;
#endif

struct csv_whitespace : std::ctype<CharacterType>
{
bool do_is(mask m, char_type c) const
{
if ((m & space) && c == ' ')
{
return false; // space will NOT be classified as whitespace
}

return ctype::do_is(m, c); // leave the rest to the parent class
}
};

int main()
{
std::basic_string<CharacterType> token;

consoleOut << "locale with modified ctype:\n";
std::basic_istringstream<CharacterType> s2(in);
s2.imbue(std::locale(s2.getloc(), new csv_whitespace()));
while (s2 >> token)
{
consoleOut << " " << token << '\n';
}
}

最佳答案

谢谢!

我根据您提供的链接执行了以下代码,并且确实有效。

#include <iostream>
#include <vector>
#include <locale>
#include <sstream>

// This ctype facet declassifies spaces as whitespace
struct CSV_whitespace : std::ctype<char>
{
static const mask* make_table()
{
// make a copy of the "C" locale table
static std::vector<mask> v(classic_table(), classic_table() + table_size);

// space will not be classified as whitespace
v[' '] &= ~space;

return &v[0];
}

CSV_whitespace(std::size_t refs = 0) : ctype(make_table(), false, refs) {}
};

int main()
{
std::string token;

std::string in = "string1\tstring2 string3";

std::cout << "locale with modified ctype:\n";
std::istringstream s(in);
s.imbue(std::locale(s.getloc(), new CSV_whitespace()));
while (s >> token)
{
std::cout << " " << token << '\n';
}
}

关于c++ - Facet ctype、do_is() 和特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22873106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com