【问题标题】:Using boost::iequals with std::u16string将 boost::iequals 与 std::u16string 一起使用
【发布时间】:2017-04-23 00:58:16
【问题描述】:

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

我做错了什么?

【问题讨论】:

    标签: c++ boost locale


    【解决方案1】:

    std::u16string 使用 char16_t(如您所知)。

    boost::iequals 在内部使用std::toupper 来比较两个字符串。

    std::toupper 需要在std::ctype&lt;cT&gt; 中的方面支持,在我们的例子中是ct = char16_t。正如answer 中所解释的那样,标准不需要这种支持,因此在大多数实现中都缺乏这种支持。

    facet std::ctype 需要专门化并放入使用的 facet 以支持字符类型的加宽、变窄和分类。 char16_t 或 char32_t 没有现成的特化。

    所以你没有做错任何事,只是没有支持。如果您确实需要 16 位 unicode 字符串支持,我建议您查看第三方库,例如 Qt,其中 QString 类使用 16 位字符 by default

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-06
      • 2011-09-14
      • 2020-08-03
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      相关资源
      最近更新 更多