为什么以下代码生成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
使用char
或wchar
而不是char32_t
跑而不扔(证据:https://ideone.com/OBlXed)。
你可以在这里找到:http://en.cppreference.com/w/cpp/regex/regex_traits:
要将std :: basic_regex与其他字符类型(例如,char32_t)一起使用,必须使用用户提供的特征类。
所以你必须实现std::regex_traits<char32_t>
并看看为什么没有定义,请看这里:Why is there no definition for std::regex_traits<char32_t> (and thus no std::basic_regex<char32_t>) provided?
在GCC或Clang上,即使使用自定义正则表达式特征,代码编译也很好,但在运行时使用std::bad_cast
失败。如果你有自己的问题,问题来自std::use_facet<std::ctype<char32_t>>
抛出错误,因为当前的语言环境不支持它。您必须专门化std::ctype<char32_t>
并通过std::locale::global
将全局语言环境设置为使用旧语言和专用方面构造的新语言环境。