Basic_regex抛出带有char32_t的bad_cast

basic_regex throws bad_cast with char32_t

本文关键字:cast char32 bad regex Basic      更新时间:2023-10-16

为什么下面的代码会产生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)。

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

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

所以你必须实现std::regex_traits<char32_t>

为什么没有std::regex_traits(因此没有提供std::basic_regex) ?

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