I have a abstract base class A and a set of 10 derived classes. The infix operator is overloaded in all of the derived classes
class A{
public:
void printNode( std::ostream& os )
{
this->printNode_p();
}
protected:
virtual void printNode_p( std::ostream& os )
{
os << (*this);
}
};
There is a container which stores the base class pointers. I want to use boost::bind function to call the overloaded infix operator in each of its derived class. I have written like this
std::vector<A*> m_args
....
std::ostream os;
for_each( m_args.begin(), m_args.end(), bind(&A::printNode, _1, os) );
What is the problem with this code? In visual studio i am getting an error like this
error C2248:
‘std::basic_ios<_Elem,_Traits>::basic_ios’
: cannot access private member
declared in class
‘std::basic_ios<_Elem,_Traits>’
Thanks,
Gokul.
Consider this, which works as expected:
First off, since you’re using boost you may as well use
ptr_vectorto handle memory management for you. So, that’s in there.Secondly, your error is because streams are not copyable; however,
boost::bindwill make a copy of all it’s arguments when constructing the functor. Wrap it in aboost::reference_wrapper(using theboost::refutility function), which is copyable. When the time comes, the wrapper will convert to the necessary type and you won’t notice the difference.(This is one of the situations
boost::refwas made for.)That all said, consider using
BOOST_FOREACH, which in my opinion generates the cleanest code: