Paul Wolfgang - Integration of the Standard Template Library and the Microsoft Foundation Class
Здесь есть возможность читать онлайн «Paul Wolfgang - Integration of the Standard Template Library and the Microsoft Foundation Class» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:Integration of the Standard Template Library and the Microsoft Foundation Class
- Автор:
- Жанр:
- Год:неизвестен
- ISBN:нет данных
- Рейтинг книги:4 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 80
- 1
- 2
- 3
- 4
- 5
Integration of the Standard Template Library and the Microsoft Foundation Class: краткое содержание, описание и аннотация
Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Integration of the Standard Template Library and the Microsoft Foundation Class»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.
Integration of the Standard Template Library and the Microsoft Foundation Class — читать онлайн бесплатно полную книгу (весь текст) целиком
Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Integration of the Standard Template Library and the Microsoft Foundation Class», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
Paul Wolfgang, Yang Song
Integration of the Standard Template Library and the Microsoft Foundation Class
1 Introduction
Both the Microsoft Foundation Class (MFC) [1] and the Standard Template Library (STL) [2] provide generalized containers and a facility to iterate over all of the objects within a container. However, the approach taken is different. Within the MFC the iteration mechanism is dependent upon the container, while in the STL there is a common iteration mechanism so that an algorithm can operate on each element of a container without knowledge of the container's type. The MFC containers support persistent storage, which is not a feature of the STL.
This paper presents a small example of a Windows® application using the STL containers in place of the corresponding MFC containers.
2 Example – Scribble.
2.1 Description of the Problem
The MFC Tutorial [3] includes a simple graphics application known as Scribble. The purpose of Scribble is to let the user draw a set of strokes with the mouse. The result is saved in a file (called a document) which can be opened and updated by adding additional strokes. (There is no method for deleting a stroke.) The user also has the option of specifying the thickness and color of the pen.
Scribble's data structure consists of one or more strokes. Each stroke is the record of the mouse position from the time when the user clicks on left mouse key to the time when the user releases the mouse button. In MFC approach, a new class CStroke, which is derived from class CObject, is defined. This contains a data member of CArray‹CPoint, CPoint› with other data members to record and work on each stroke. The document class, CScribbDoc, is derived from CDocument. It contains a list of stokes using the MFC template class CTypedPtrList‹CObList, CStroke*›.
Figure 1 illustrates the document data structure.
Figure 1 Scribble Document Structure
2.2 Type definitions
2.2.1 MFC Implementation
In the MFC implementation, the list of strokes is stored in the member m_strokeList which is defined as a CTypedPtrList‹CObject, CStroke*›. The class CStroke, in turn, contains a CArray‹CPoint, CPoint› to contain the array of points that constitute the stroke.
2.2.2 STL Implementation
The class CStrokeList is defined to replace the CTypedPtrList‹CObject, CStroke*› as follows:
class CStrokeList: public CObject, public std::list‹CStroke*›
{
public:
CStrokeList () {}
CStrokeList(const CStrokeList&);
DECLARE_SERIAL(CStrokeList)
public:
virtual
void Serialize(CArchive& ar);
};
The CArray‹CPoint, CPoint› in CStroke is replaced by a std::list‹CPoint›.
2.3 Using the STL algorithms and iterators
2.3.1 Inserting points into a stroke
In the original MFC implementation, points were added to a stroke by the following statement:
m_pStrokeCur-›m_pointArray.Add(point);
In the STL implementation this becomes:
m_pStrokeCur-›m_pointArray.push_back(point);
2.3.2 Drawing all strokes
In the original MFC implementation, the list of strokes was traversed and each stroke drawn by the following code:
POSITION pos = strokeList.front ();
while (pos!= NULL)
{
CStroke* pStroke =
strokeList.GetNext(pos);
pStroke-›DrawStroke(pDC);
}
We make two changes. The first obvious change is to replace the MFC list iteration with the corresponding STL iteration. The result is as follows:
for (std::list‹CStroke*›::iterator i = strokeList.begin(); i!= strokeList.end(); ++i)
(*i)-›DrawStroke(pDC);
The second change is to apply the for_each algorithm. Unfortunately, the for_each algorithm takes as its third argument a function of one argument, that argument being the type obtained by de-referencing the iterator. Specifically, we must convert the expression:
(*i)-›DrawStroke(pDC);
into a call to a function of one argument, where that argument is the dereferenced iterator. Stroustrup[4] shows how to do this using the binders and adapters. The function mem_fun1 is a function of one parameter, the a pointer to member function that takes an arbitrary argument. The result of this function, is a function object that takes two arguments, the first of which is a pointer to a class, and the second is the same arbitrary second argument. Thus, the expression
(*i)-›DrawStroke(pDC);
may be replaced by
mem_fun1(&CStroke::DrawStroke)(*i, pDC);
We can now apply the bind2nd binder to convert this expression into a call to a function taking one argument:
bind2nd(mem_fun1(&CStroke::DrawStroke), pDC)(*i);
The loop can now be replaced by a call to the for_each algorithm:
for_each(strokeList.begin(), strokeList.end(), bind2nd(mem_fun1(&CStroke::DrawStroke), pDC));
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(&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 =&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));
2.4 Serialization
2.4.1 Brief description of the MFC serialization
MFC provides a method for saving and retrieving a class to/from a file. The general approach is to write/read the raw bytes to the file preceded by some type identification. This is accomplished using the class CObject as an abstract base class, the virtual function serialize, and the class CArchive. CArchive encapsulates the file and provides overloaded insertion (‹‹) and extraction (››) operators. These operators are provided for the built-in types, the standard Windows® types such as WORD, DWORD, and POINT, and pointers to CObject. The insertion operator for pointers to CObject writes type identification to the file, and then calls the serialize member function. The extraction operator verifies the type identification and then calls the serialize member function.
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Integration of the Standard Template Library and the Microsoft Foundation Class»
Представляем Вашему вниманию похожие книги на «Integration of the Standard Template Library and the Microsoft Foundation Class» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Integration of the Standard Template Library and the Microsoft Foundation Class» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.