Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::bad_cast thrown by boost::locale?

I try to understand how to use boost::locale to compare strings ignoring case and variants. I directly tried a code from Boost documentation :

http://www.boost.org/doc/libs/1_51_0/libs/locale/doc/html/collation.html

boost::locale::generator gen;
std::locale vLocale = gen("");


std::wstring a=L"Façade", b=L"facade";

// Following will throw bad_cast
bool eq = std::use_facet<boost::locale::collator<wchar_t>>(vLocale).compare(
    boost::locale::collator_base::secondary,
    a,
    b
) == 0;

if(eq) std::cout << "OK" << std::endl;

This code will throw a std::bad_cast exception when running. I tried a lot of parameters in the constructor of boost::locale::generator. Does anyone know about the problem I encounter ?

I am using C++11 with g++4.6 and Boost 1.51.0

like image 270
Oragon Efreet Avatar asked Oct 29 '12 22:10

Oragon Efreet


1 Answers

It seems you are using an incorrect locale object. First, you should use global locale and then (if you want to use std::cout) imbue the locale to the stream. Something like this:

boost::locale::generator gen;
std::locale loc = gen("");
std::locale::global(loc);

But, in your example, if you are not using std::cout, just set global locale so you have the required facets ready.

like image 147
Oleksandr Karaberov Avatar answered Oct 24 '22 21:10

Oleksandr Karaberov