A Macro Technique for Managing Types
Dr. Dobb's Journal July 1997
By Mayur Patel
In the image-processing architecture presented here, I use a macro technique to encapsulate data type support. Like any macro technique, it requires disciplined use. However, it provides a convenient way to make branching decisions based on type information.
C/C++ programmers are familiar with the source-header file combination. To implement this macro technique, I need another kind of file. I call this a macro file, and I use a ".m" extension. Some choose to call it an include file, with a ".i" extension.
There are three things to notice in Listing Four, which is an example macro file I call "Type.m." First, all macros are undefined by the end of the file. Second, the macro TYPEMACRO is not defined within this file, even though it is used. TYPESEPER and TYPEENDOFLIST are defined only if they haven't already been instantiated. Third, one of the elements in the TYPEMACRO is a formal data type.
The parameters to the TYPEMACRO calls encapsulate a table of information. Depending on your application, you will need different information in this table. The trick is to keep this table minimal. In the image-processing architecture, I had to include function names, numeric values, and precedence information.
Listing Five shows one way you can use the macro file in Listing Four. This bit of code declares an enumeration that can be used to identify and manage types in a cleaner way in other parts of the code. The TYPEMACRO definition allows information to be extracted from the table in the Type.m file and used in the current context. The TYPESEPER and TYPEENDOFLIST elements allow the included table entries to adapt to the syntax of their context. Listing Six illustrates another way to use the macro file in Listing Four.
The application uses the enumerated type declared earlier to provide type information when the function is invoked. In this case, data is available through void pointers, but in general, any interface that supports easy typecasting will work. The macro definition and include statement fill the switch with a variety of alternative behaviors, depending upon the specified type.
I originally learned this technique while implementing databases, but it clearly can be applied to a wide variety of situations. With sparing, disciplined use, it can be a powerful tool for managing types in C/C++.
-- M.P.
Dr. Dobb's Journal July 1997
Copyright © 1997, Dr. Dobb's Journal