Boost Binding Function

I have an abstract base class A and a set of 10 derived classes. The infix statement is overloaded in all 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 in which the base class pointers are stored. I want to use the boost :: bind function to call the overloaded infix operator in each of its derived class. I wrote 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 get an error

error C2248: 'STD :: basic_ios <_Elem, _Traits> :: basic_ios': cannot access a private member declared in the class 'STD :: basic_ios <_Elem, _Traits>'

Thanks, Gokul.

+3
source share
2 answers

, :

#include <iostream>

struct base
{
    virtual ~base(void) {}

    virtual void print(std::ostream& pStream) = 0;
};

struct foo : base
{
    void print(std::ostream& pStream) { pStream << "foo" << std::endl; }
};

struct bar : base
{
    void print(std::ostream& pStream) { pStream << "bar" << std::endl; }
};

#include <boost/bind.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <algorithm>

int main(void)
{
    boost::ptr_vector<base> v;
    v.push_back(new foo);
    v.push_back(new bar);

    std::for_each(v.begin(), v.end(),
                  boost::bind(&base::print, _1, boost::ref(std::cout)));
}

-, boost, ptr_vector . , .

-, , ; boost::bind . boost::reference_wrapper ( boost::ref), . , , .

( boost::ref .)


, BOOST_FOREACH, , , :

#include <boost/foreach.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <algorithm>

#define foreach BOOST_FOREACH

int main(void)
{
    boost::ptr_vector<base> v;
    v.push_back(new foo);
    v.push_back(new bar);

    foreach (base* b, v)
    {
        v->print(std::cout);
    }
}
+5

, std:: ostream . :

for_each( m_args.begin(), m_args.end(), bind(&A::printNode, _1, boost::ref(os) ) );

, Gokul.

0

Source: https://habr.com/ru/post/1739932/


All Articles