basic_regex使用char32_t抛出bad_cast

时间:2022-09-10 23:23:05

Why does the following code generate std::bad_cast exception?

为什么以下代码生成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;
}

This sample on Ideone for convenience: https://ideone.com/Saea88

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

Using char or wchar instead of char32_t runs without throwing though (proof: https://ideone.com/OBlXed).

使用char或wchar代替char32_t但不会抛出(证明:https://ideone.com/OBlXed)。

1 个解决方案

#1


2  

You can find here: http://en.cppreference.com/w/cpp/regex/regex_traits:

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

To use std::basic_regex with other character types (for example, char32_t), a user-provided trait class must be used.

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

so you would have to implement std::regex_traits<char32_t>

所以你必须实现std :: regex_traits

and to see why there is no definition for it see here: Why is there no definition for std::regex_traits<char32_t> (and thus no std::basic_regex<char32_t>) provided?

并且看看为什么没有定义它在这里看:为什么没有提供std :: regex_traits (因此没有std :: basic_regex )的定义?

#1


2  

You can find here: http://en.cppreference.com/w/cpp/regex/regex_traits:

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

To use std::basic_regex with other character types (for example, char32_t), a user-provided trait class must be used.

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

so you would have to implement std::regex_traits<char32_t>

所以你必须实现std :: regex_traits

and to see why there is no definition for it see here: Why is there no definition for std::regex_traits<char32_t> (and thus no std::basic_regex<char32_t>) provided?

并且看看为什么没有定义它在这里看:为什么没有提供std :: regex_traits (因此没有std :: basic_regex )的定义?