【问题标题】:Increment boost::variant value递增 boost::variant 值
【发布时间】:2016-05-30 13:36:45
【问题描述】:

我有一个变体变量,其中不同的类型都实现了operator++。我想直接对变量变量应用增量。有没有简单的方法可以做到这一点?还是我必须在每种类型的开关中应用它?

带有stl迭代器的简单示例

typedef boost::variant<
  std::vector<double>::iterator,
  std::vector<double>::reverse_iterator,
  std::set<double>::iterator,
  std::set<double>::reverse_iterator
> AnyIterator;

void incr(AnyIterator& ai)
{
  ++adi; // this doesn't compile: no match for operator++ blah blah blah

  // Have I really to write this kind of ugly thing ?
  if(ai.type() == typeid(std::vector<double>::iterator))
    ++boost::get<std::vector<double>::iterator>(ai);
  else if(ai.type() == typeid(std::vector<double>::reverse_iterator))
    ++boost::get<std::vector<double>::reverse_iterator>(ai);
  else if(ai.type() == typeid(std::set<double>::iterator))
    ++boost::get<std::set<double>::iterator>(ai);
  else if(ai.type() == typeid(std::set<double>::reverse_iterator))
    ++boost::get<std::set<double>::reverse_iterator>(ai);
}

注意:我使用 gcc 4.8.1 和 Boost 1.57。我不想要 C++11 的解决方案,由于与旧 gcc 版本的兼容性,我无法使用它。

【问题讨论】:

  • 我认为您无法摆脱编写这种丑陋的代码,但如果您经常需要它,您可以为您的 AnyIterator 类型实现 ++ 运算符。

标签: c++ boost c++98 boost-variant


【解决方案1】:

您可以定义一个通用仿函数,然后将boost::apply_visitor 与该仿函数一起使用:

namespace detail {
struct incrementer {
    template< typename T >
    void operator()(T& x) const { ++x; }
    typedef void result_type;
};
}

void incr(AnyIterator& ai)
{
  boost::apply_visitor(detail::incrementer(),ai);
}

【讨论】:

  • 我明白了。看起来很简单。您可以尝试编译您的解决方案吗?我有一个关于模板推导的编译错误,注释中有几个命题(评论太长)。此外,为什么要将结构放在命名空间 detail 中?这只是不好的做法吗?出于什么原因?
  • @Caduchon I see no error。命名空间detail 确实是不必要的。
  • 他妈的上帝!我错过了typedef void return_type;。这个错误真是无法理解!谢谢,现在可以使用了。
  • 似乎更好的方法是从boost::static_visitor&lt;&gt;继承。但想法就在那里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
  • 1970-01-01
相关资源
最近更新 更多