【问题标题】:Using for_each and boost::bind with a vector of pointers使用带有指针向量的 for_each 和 boost::bind
【发布时间】:2010-03-10 00:56:19
【问题描述】:

我有一个指针向量。我想为每个元素调用一个函数,但该函数需要一个引用。有没有一种简单的方法来取消引用元素?

例子:

MyClass::ReferenceFn( Element & e ) { ... }

MyClass::PointerFn( Element * e ) { ... }

MyClass::Function()
{
    std::vector< Element * > elements;
    // add some elements...

    // This works, as the argument is a pointer type
    std::for_each( elements.begin(), elements.end(),
                   boost::bind( &MyClass::PointerFn, boost::ref(*this), _1 ) );

    // This fails (compiler error), as the argument is a reference type
    std::for_each( elements.begin(), elements.end(),
                   boost::bind( &MyClass::ReferenceFn, boost::ref(*this), _1 ) );
}

我可以创建一个带有指针的脏小包装器,但我认为必须有更好的方法?

【问题讨论】:

  • 您使用boost::ref(*this) 有什么原因吗?我只是使用: boost::bind(&MyClass::ReferenceFn, this, _1) 它工作正常。

标签: c++ boost boost-bind


【解决方案1】:

你可以使用boost::indirect_iterator:

std::for_each( boost::make_indirect_iterator(elements.begin()), 
               boost::make_indirect_iterator(elements.end()),
               boost::bind( &MyClass::ReferenceFn, boost::ref(*this), _1 ) );

这将在其operator* 中取消引用适应的迭代器两次。

【讨论】:

  • +1,尽管在这种情况下我更喜欢BOOST_FOREACH(Element *e, elements) this-&gt;ReferenceFn(*e);。 C++ 可以用作函数式语言,但不能用作简洁函数式语言...
  • Python 将是for e in elements: self.ReferenceFn(e)。令人心碎。
  • 对于 C++0x,它将是 for(auto *e : elements) ReferenceFn(*e);。甜:)
  • 我正在考虑开始称它为 C++JamTomorrow。
【解决方案2】:

看来您也可以使用Boost.Lambda 库。

// Appears to compile with boost::lambda::bind
    using namespace boost::lambda;
    std::for_each( elements.begin(), elements.end(),
                   bind( &MyClass::ReferenceFn, boost::ref(*this), *_1 ) );

但我同意评论者关于更喜欢BOOST_FOREACH 的观点。 for_each“算法”实际上没有任何用处,而它所做的,基于范围的 for 循环可以为您做更少的工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-06
    • 2013-07-09
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    • 2013-10-05
    相关资源
    最近更新 更多