Using for_each and boost::bind with a vector of pointers

痞子三分冷 提交于 2019-12-06 23:27:44

问题


I have a vector of pointers. I would like to call a function for every element, but that function takes a reference. Is there a simple way to dereference the elements?

Example:

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

I could create a dirty little wrapper that takes a pointer, but I figured there had to be a better way?


回答1:


You could use 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 ) );

That will dereference the adapted iterator twice in its operator*.




回答2:


It looks like you could also use the Boost.Lambda library.

// 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 ) );

But I agree with the commenters about preferring BOOST_FOREACH. The for_each "algorithm" does practically nothing useful, and what it does, range-based for loop can do for you with a much smaller effort.



来源:https://stackoverflow.com/questions/2413786/using-for-each-and-boostbind-with-a-vector-of-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!