组合boost :: exception和boost :: variant的问题

时间:2011-03-12 23:33:50

标签: c++ exception boost variant

当包含b​​oost :: exception时,我有两级变量struct的奇怪问题。我有以下代码段:

#include <boost/variant.hpp>
#include <boost/exception/all.hpp>

typedef boost::variant< int >   StoredValue;
typedef boost::variant< StoredValue > ExpressionItem;
inline std::ostream& operator << ( std::ostream & os, const StoredValue& stvalue ) {    return os;}
inline std::ostream& operator << ( std::ostream & os, const ExpressionItem& stvalue ) { return os; }

当我尝试编译它时,我有以下错误:

boost/exception/detail/is_output_streamable.hpp(45): error C2593: 'operator <<' is ambiguous
test.cpp(11): could be 'std::ostream &operator <<(std::ostream &,const ExpressionItem &)' [found using argument-dependent lookup]
test.cpp(8): or       'std::ostream &operator <<(std::ostream &,const StoredValue &)' [found using argument-dependent lookup]
1>  while trying to match the argument list '(std::basic_ostream<_Elem,_Traits>, const boost::error_info<Tag,T>)'
1>  with
1>  [
1>    _Elem=char,
1>    _Traits=std::char_traits<char>
1>   ]
1>   and
1>   [
1>       Tag=boost::tag_original_exception_type,
1>       T=const type_info *
1>   ]

尽可能简化代码片段,在实际代码中结构更加复杂,每个变体都有五个子类型。

当我删除#include boost / exception / all并尝试关注测试片段时,程序编译正确:

void TestVariant()
{
  ExpressionItem test;
  std::stringstream str;
  str << test;
}

有人可以告诉我如何定义运算符&lt;&lt;为了在使用boost :: Exception时起作用?

谢谢和问候

瑞克

1 个答案:

答案 0 :(得分:0)

我不认为它与boost :: exception有任何关系。它是输出流“operator&lt;&lt;”。但我没有使用变体,因为你正在使用它 - 只有一种类型;我认为你应该至少有两种类型,因为这是一种“类固醇联合”,但也许有一些隐含的东西......我会重温这些文档。

您的代码是否在boost命名空间内?我认为您的输出流运算符与为异常定义的运算符冲突。尝试将代码放在自己的命名空间中。

对于未被执行的操作员,可能仍然是选错了的问题...尝试使用“&lt;&lt;”运算符通过在命名空间和分辨率运算符前面添加前缀,就像使用 std :: stringstream。

一样。

编辑:作为上一条评论的后续内容:您可以在自己的命名空间中定义运算符,例如 mynamespace ,然后在需要时显式使用您的版本,例如

void TestVariant()
{
  using namespace mynamespace;

  ExpressionItem test;
  std::stringstream str;
  str << test;
}

它可以与上面提到的例子一起使用,但我不确定是否;那是你面临的确切情况......而且我对精神不是很熟悉