"Integration of the Standard Template Library and the Microsoft Foundation Class" - читать интересную книгу автора (Wolfgang Paul, Song Yang)

2.3.3 Drawing a stroke

The original code to draw a stroke was as follows:

pDC-›MoveTo(m_pointArray[0]);

for (int i=1; i ‹ m_pointArray.GetSize(); i++) {

 pDC-›LineTo(m_pointArray[i]);

}

We also make two changes. The first is to use the vector iterator as follows:

pDC-›MoveTo(m_pointArray.begin());

for (vector‹CPoint›::iterator i= m_pointArray.begin(); i!= m_pointArray.end(); ++i)

 pDC-›LineTo(*i);

Now the member function we are calling is not a member of the class pointed to by the objects in the container, but rather it is a member of the class CDC, which encapsulates the Windows® drawing context. The same mem_fun1 adapter may be used as follows:

mem_fun1(amp;CDC::LineTo) (pDC, *i);

Since LineTo is an overloaded function, we need to give the compiler some help resolving the ambiguity. This is done as follows:

typedef BOOL (CDC::*ptr_to_fcn_of_POINT) (POINT);

ptr_to_fcn_of_POINT p =amp;CDC::LineTo;

mem_fun1(p)(pDC, *i)

Since the loop variable is now the second argument, and the pDC is the first, we use bind1st to call the for_each algorithm as follows:

for_each(m_pointArray.begin(), m_pointArray.end(), bind1st(std::mem_fun1(p), pDC));