0

当包含 boost::exception 时,我对两级变体结构有奇怪的问题。我有以下代码片段:

#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;
}

有人可以告诉我如何定义运算符 << 以便即使在使用 boost::Exception 时也能正常工作?

谢谢并恭祝安康

瑞克

4

1 回答 1

0

我认为这与 boost::exception 没有任何关系。它是输出流“运算符<<”。但是我没有像您使用它那样使用该变体-只有一种类型;我认为你应该至少有 2 种类型,因为这是“类固醇联合”,但也许有一些隐含的东西......我会重新访问文档。

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

至于未执行的运算符,它可能仍然是选择错误的问题...尝试使用您的“<<”运算符,方法是在它前面加上命名空间和解析运算符,就像使用std::stringstream 一样。

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

void TestVariant()
{
  using namespace mynamespace;

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

它适用于上述示例,但我不确定这是否是您所面临的确切情况......而且我对精神不是很熟悉

于 2011-03-13T08:25:00.390 回答