【问题标题】:basic_regex throws bad_cast with char32_tbasic_regex 用 char32_t 抛出 bad_cast
【发布时间】:2016-08-24 14:55:26
【问题描述】:

为什么下面的代码会产生std::bad_cast异常?

#include <iostream>
#include <regex>
#include <string>

int main()
{
    std::basic_string<char32_t> reg = U"^\\w";

    try
    {
        std::basic_regex<char32_t> tagRegex(reg);
    }
    catch(std::exception &e)
    {
        std::cout << e.what() << std::endl;
    }

    return 0;
}

为方便起见,此示例在 Ideone 上:https://ideone.com/Saea88

使用charwchar 代替char32_t 运行时不会抛出异常(证明:https://ideone.com/OBlXed)。

【问题讨论】:

    标签: c++ regex casting stdstring


    【解决方案1】:

    您可以在这里找到:http://en.cppreference.com/w/cpp/regex/regex_traits:

    要将 std::basic_regex 与其他字符类型(例如 char32_t)一起使用,必须使用用户提供的 trait 类。

    所以你必须实现std::regex_traits&lt;char32_t&gt;

    要了解为什么没有它的定义,请参见此处:Why is there no definition for std::regex_traits<char32_t> (and thus no std::basic_regex<char32_t>) provided?

    【讨论】:

      【解决方案2】:

      在 GCC 或 Clang 上,即使使用自定义正则表达式特征,代码也能正常编译,但在运行时会因 std::bad_cast 而失败。如果您在这里,问题来自std::use_facet&lt;std::ctype&lt;char32_t&gt;&gt; 抛出错误,因为当前语言环境不支持它。您必须专门化 std::ctype&lt;char32_t&gt; 并通过 std::locale::global 将全局语言环境设置为使用旧语言和专用方面构建的新语言环境。

      【讨论】:

      • 您能举个例子吗?
      • @AlexAngel 你可以找到一个有效的实现herehere
      猜你喜欢
      • 2014-11-28
      • 2013-07-11
      • 2016-02-15
      • 2023-03-28
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 2011-04-06
      • 2014-04-11
      相关资源
      最近更新 更多