2013-05-02 125 views
2

在嘗試添加對庫中UTF-8語言環境的支持時,我將 類型std::wstring添加到包含值的boost::variantboost :: variant無法處理字符串和字符串

在這一點上,我開始進去boost::variant的東西倒錯誤:

Blockquote/opt/TWWfsw/libboost147/include/boost/variant/detail/variant_io.hpp: In member function 'void boost::detail::variant::printer::operator()(const T&) const [with T = std::basic_string, std::allocator >, OStream = std::basic_ostream >]':
/opt/TWWfsw/libboost147/include/boost/variant/variant.hpp:858: instantiated from 'typename Visitor::result_type boost::detail::variant::invoke_visitor::internal_visit(T&, int) [with T = const std::basic_string, std::allocator >, Visitor = boost::detail::variant::printer > >]'
< SNIP SNIP >
Cursor.H:84: instantiated from here /opt/TWWfsw/libboost147/include/boost/variant/detail/variant_io.hpp:64: error: no match for 'operator<<' in '((const boost::detail::variant::printer > >)this)->boost::detail::variant::printer > >::out_ << operand'
/opt/TWWfsw/gcc44/include/c++/ostream:108: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (
)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits]
etc.

這個例子是使用升壓1.47瓦特/ G ++ 4.4。

#include <string> 
#include <iostream> 
#include <boost/variant.hpp> 
#define NO_STRING 1 

int main (int argc, char** argv) 
{ 
#if defined(NO_STRING) 
    boost::variant<int, std::wstring> v; 
#else 
    boost::variant<int, std::wstring, std::string> v; 
#endif 
    v = 3; 
    std::wcout << v << std::endl; 
    std::wstring T(L"wide char literal"); 
    v = T; 
    std::wcout << v << std::endl; 
    return 0; 
} 

這一計劃將輸出:

3
wide char literal

但如果#define被刪除,並且兩個stringwstring都在變異模板參數,相同的錯誤結果。

我的問題是,我可以創造的東西,將滿足這個失蹤的定義,就像一個模板特殊化?

也許定義一個變種是訪問者轉換寬字符串到一個窄字符串? (不是一般的解決辦法,但會縮小在我的情況下工作)

的問題來自使用<<與變種兩個字符串的定義時。即使我只通過變體輸出int,它也不會編譯。

回答

1

您的問題不是boost::variant不能同時處理stringwstring。問題是wcout無法處理std::string。有關詳細信息,請參見Why is it that wcout << ""; is OK but wcout << string(); is not?

+0

因此,即使變體不包含std :: string值,也不能在「wcout <<」中使用。相反,這也意味着它不能用於「cout <<」或任何流式插入操作。這不*嚴厲*限制boost :: variant的有用性嗎?基本上我必須有應用程序,其中所有字符串都很寬,或者所有字符串都很窄。 – 2013-05-03 14:38:21

+0

這不是使用「wcout」是問題,如果我修改程序以使用std :: cout並輸出int值變體,則會發生相同的錯誤。 – 2013-05-03 15:34:11

+0

wcout wstring的與作品,作品的cout用繩子 – 2013-05-04 20:44:21