Chapter 3 -- C Templates

[Previous] [Next]

Chapter 3

After reading Chapter 2, you should have a pretty firm grasp of COM, and you should be sold on its benefits (we hope). Recall that COM is really just Microsoft's brand of interface-based programming. The primary distinction between interface-based programming and class-based programming (the kind C++ programmers have been doing for the last decade) is that in interface-based programming a class's implementation is separated from its interface.

One downside of COM is that getting a COM class up and running requires substantial amounts of boilerplate code. To write a COM class, you need to perform the following tasks:

  • Write the COM class, implementing IUnknown correctly.
  • Add IDispatch (or a dual interface) if the object is to be available to a scripting environment.
  • Write a class object (which implements IClassFactory in most cases).
  • Add a reference-counting mechanism to the server.
  • Add self-registration code to the server.
  • Add the correct entry points if the server is a DLL: DllGetClassObject, DllCanUnloadNow, DllRegisterServer, and DllUnregisterServer.
  • Add calls to CoRegisterClassObject if the server is an EXE.

As you can see, just as writing a regular Win32 SDK_type application requires reams of infrastructure code, so does writing a COM DLL or EXE involve a huge amount of infrastructure code that stays mostly the same from one COM class to another.

Code reuse has been the mantra of programmers since time began. Why should we have to retype lots of code for lots of different classes when most of the code is going to be the same in every class? With C++ templates, we don't have to.

Developers are always looking for ways to reduce the amount of typing they need to do. C and C++ developers have been using preprocessor macros to abstract and generalize code for years. If you write a macro, the preprocessor simply substitutes the code the macro defines whenever the macro is used in the code. Macros basically save you a whole bunch of typing. The biggest problem with macros is that they are often difficult to get right and to debug. C++ templates are like macros in that they also facilitate abstracting and generalizing C++ code. However, templates are C++ language-specific and are handled by the compiler (rather than the preprocessor) and so are type-safe.

In this chapter, we'll cover the philosophy behind C++ templates and explain how to use them. This information is important for you to know because Microsoft Active Template Library (ATL) is based heavily on C++ templates.



Inside Atl
Inside ATL (Programming Languages/C)
ISBN: 1572318589
EAN: 2147483647
Year: 1998
Pages: 127

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net