【发布时间】:2018-03-21 19:27:32
【问题描述】:
我正在编写一些单元测试时,偶然发现了一个已经成功地困扰了我几次的场景。
我需要生成一些字符串来测试 JSON 写入器对象。由于作者同时支持 UTF16 和 UTF8 输入,我想同时测试一下。
考虑以下测试:
class UTF8;
class UTF16;
template < typename String, typename SourceEncoding >
void writeJson(std::map<String, String> & data)
{
// Write to file
}
void generateStringData(std::map<std::string, std::string> & data)
{
data.emplace("Lorem", "Lorem Ipsum is simply dummy text of the printing and typesetting industry.");
data.emplace("Ipsum", "Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book");
data.emplace("Contrary", "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old");
}
void generateStringData(std::map<std::wstring, std::wstring> & data)
{
data.emplace(L"Lorem", L"Lorem Ipsum is simply dummy text of the printing and typesetting industry.");
data.emplace(L"Ipsum", L"Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book");
data.emplace(L"Contrary", L"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old");
}
template < typename String, typename SourceEncoding >
void testWriter() {
std::map<String, String> data;
generateStringData(data);
writeJson<String, SourceEncoding>(data);
}
int main() {
testWriter<std::string, UTF8>();
testWriter<std::wstring, UTF16>();
}
除了重复的generateStringData() 方法外,我设法很好地包装了所有内容。 如果可以将两种 generateStringData() 方法组合成一个方法,我正在徘徊?
我知道我可以使用一种方法以 UTF8 生成字符串,然后使用其他方法将字符串转换为 UTF16,但我正在尝试找出是否有其他方法。
我考虑过/尝试过什么?
- 使用
_T()或TCHAR或#ifdef UNICODE无济于事,因为我需要在支持 Unicode 的同一平台上使用这两种风格(例如 Win >= 7) - 从不是
L""的东西初始化std::wstring将不起作用,因为它需要 wchar_t - 按字符初始化字符不起作用,因为它还需要
L'' - 使用
""s将不起作用,因为返回类型取决于charT类型
【问题讨论】:
-
UTF-8 和 UTF-16 字符串对于给定的非 ASCII 文本不包含相同的字节。您的测试用例只包含 7 位 ASCII,它们没有用。
-
@manni66,这些是一些虚拟值,这不是这个问题的本质......
-
推荐使用 UTF-8 来读写网页相关数据。如果您必须使用 UTF-16,则将文件逐行写入 UTF-8,并在整个文件上运行最终的 UTF-16 转换(但如果文件大于 2 gig,则会失败)。
-
@BarmakShemirani,这不是网络相关数据。这是从 Windows 获取的信息,某些 API 默认使用 wchar_t。
-
预处理器是唯一可行的方法,恐怕。 I had a similar issue once.