2017-04-23 65 views
0

我試圖做兩個std :: u16string實例與boost,不區分大小寫的字符串比較。基於我的搜索,我需要生成一個語言環境,我正在做。與std :: u16string一起使用boost :: iequals

#include <boost/algorithm/string.hpp> 
#include <boost/locale.hpp> 

#include <locale> 
#include <iostream> 

int main() { 
    // Create the strings 
    std::u16string str1 = boost::locale::conv::utf_to_utf<char16_t>("unicode"); 
    std::u16string str2 = boost::locale::conv::utf_to_utf<char16_t>("UNICODE"); 

    // Create the locale 
    boost::locale::generator gen; 
    std::locale loc = gen(""); 

    // Doesn't matter if I do this or not 
    //std::locale::global(loc); 

    // Try to compare 
    if (boost::iequals(str1, str2, loc)) { 
     std::cout << "EQUAL\n"; 
    } else { 
     std::cout << "!EQUAL\n"; 
    } 

    return 0; 
} 

這導致的std :: bad_cast異常:

terminate called after throwing an instance of 'std::bad_cast' 
    what(): std::bad_cast 

我在做什麼錯?

回答

1

std::u16string使用char16_t(如你所知)。

boost::iequals在內部使用std::toupper來比較兩個字符串。

std::toupper需要方面支持std::ctype<cT>,其中ct = char16_t在我們的情況。正如answer中所解釋的那樣,該支持不是標準所要求的,因此在大多數實現中缺乏。

facet std :: ctype需要專門化並放入使用的構面中以支持字符類型的擴展,縮小和分類。 char16_t或char32_t沒有現成的專業化版本。

所以你沒有做錯任何事,支持只是不存在。如果您真的需要16位Unicode字符串支持,我建議您查看第三方庫,例如Qt,其中類QString使用16位字符by default

相關問題