The preprocessor provides two special operators for manipulating strings in macros. The stringizing operator (#) substitutes a quoted string for whatever follows the stringizing operator. The concatenation operator (##) bonds two strings together into one.
The stringizing operator(#) puts quotes around any characters following the operator, up to the next white space. So, if you write:
#define WRITESTRING(x) cout << #x
and then call
WRITESTRING(This is a string);
the precompiler will turn it into this:
cout << "This is a string";
Note that the string This is a string is put into quotes, as required by cout.
The concatenation operator (##) enables you to bond together more than one term into a new word. The new word is actually a token that can be used as a class name, a variable name, an offset into an array, or anywhere else a series of letters might appear.
Assume for a moment that you have five functions, named fOnePrint, fTwoPrint, fThreePrint, fFourPrint, and fFivePrint. You can then declare
#define fPRINT(x) f ## x ## Print
and then use it with fPRINT(Two) to generate fTwoPrint, and with fPRINT(Three) to generate fThreePrint.
At the conclusion of Hour 19, “Linked Lists,” a PartsList class was developed. This list could only handle objects of type List. Let's say that this list works well, and you'd like to be able to make lists of animals, cars, computers, and so on.
One approach would be to create AnimalList, CarList, ComputerList, and so forth, cutting and pasting the code in place. This would quickly become a nightmare, because every change to one list would have to be written to all the others.
An alternative is to use macros and the concatenation operator. For example, you could define
#define Listof(Type) class Type##List { public: Type##List(){} private: int itsLength; };
This example is overly sparse, but the idea would be to put in all the necessary methods and data. When you were ready to create an AnimalList, you would write
Listof(Animal)
and this would be turned into the declaration of the AnimalList class. There are some problems with this approach, all of which are discussed in detail in Hour 23, “Templates,” when templates are discussed.
13.58.220.83