我正在尝试使用 boost 对两个 std::u16string 实例进行不区分大小写的字符串比较。根据我的搜索,我需要生成我正在做的语言环境。
#include <boost/algorithm/string.hpp>
#include <boost/locale.hpp>
#include <locale>
#include <iostream>
int main() {
// Create the strings
std::u16string str1 = boost::locale::conv::utf_to_utf<char16_t>("unicode");
std::u16string str2 = boost::locale::conv::utf_to_utf<char16_t>("UNICODE");
// Create the locale
boost::locale::generator gen;
std::locale loc = gen("");
// Doesn't matter if I do this or not
//std::locale::global(loc);
// Try to compare
if (boost::iequals(str1, str2, loc)) {
std::cout << "EQUAL\n";
} else {
std::cout << "!EQUAL\n";
}
return 0;
}
这会导致 std::bad_cast 异常:
terminate called after throwing an instance of 'std::bad_cast'
what(): std::bad_cast
我做错了什么?
最佳答案
std::u16string
使用 char16_t
(如你所知)。
boost::iequals
使用 std::toupper
在内部比较两个字符串。
std::toupper
需要 std::ctype<cT>
中的方面支持, 其中ct = char16_t
在我们的例子中。如本 answer 中所述,标准不需要此支持,因此大多数实现中都缺少此支持。
The facet std::ctype needs to be specialized and put into the used facet to support widening, narrowing, and classification of the character type. There is no ready specialization for char16_t or char32_t.
所以您没有做错任何事,只是没有提供支持。如果您真的需要 16 位 unicode 字符串支持,我建议您查看第三方库,例如 Qt
, 类(class) QString
使用 16 位字符 by default .
关于c++ - 将 boost::iequals 与 std::u16string 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43566299/