2013-05-02 116 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