Ale*_*eem 9 c++ boost boost-bind
我有一个指针向量.我想为每个元素调用一个函数,但该函数需要引用.是否有一种简单的方法来取消引用元素?
例:
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 ) );
}
Run Code Online (Sandbox Code Playgroud)
我可以创建一个带指针的脏小包装器,但我认为必须有更好的方法吗?
Joh*_*itb 15
你可以使用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 ) );
Run Code Online (Sandbox Code Playgroud)
这将在适当的迭代器中取消两次operator*
.