c++ - 将 boost::iequals 与 std::u16string 一起使用

标签 c++ boost locale

我正在尝试使用 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/

相关文章:

c++ - 如何将 Boost UUID 随机生成器输出传递给 main

javascript - 是否可以通过 JavaScript 中的浏览器确定操作系统中设置的用户区域设置的**国家/地区**?

android - 如何在 TextTOSpeech 中设置印度英语?

android - 更改应用程序区域设置后如何获取设备区域设置

c++ - Boost::asio 这种奇怪的编码风格是什么?

c++ - 如何 boost Boost ASIO、UDP 客户端应用程序的吞吐量

c++ - 模板参数中的自引用模板

c++ - 不安全、超快的跨进程内存缓冲区?

c++ - 启动进程并稍后识别它

c++ - 从 cpp 文件创建头文件 .h