VisualCpp.org Collection of Visual C++ Stuffs

13Dec/071

Hidden MACRO secret: writing clutterfree code!?

Every body knows that macro got expanded in compilation phase. We can use Macro’s to simplifies our  programming construct and making our coding looks more professional, or making it look like it coded by genius ( self praise ha ha ha!) . Apart from jokes, many times you might be come across situation which requires you have many get/set variable inside your class, this will makes your code clutter sometime, as you have to declare the variable then write get/set function for them. You could solve this problem using macros!
Like this :-

1. Defining Macro:-

#define MYVARMACRO(VarName,VarDataType) VarDataType m_##VarName;\
 VarDataType Get##VarName() { return m_##VarName; }\
 void Set##VarName( const VarDataType & a_arg) {m_##VarName = a_arg ;}

2: Declaring macro :-


MYVARMACRO(strName,CString)

3: Calling macro function created at compile time, when macro get expanded

SetstrName(CString("VisualCPP"));
MessageBox(GetstrName());

Here ## concatenate the string at compile time, so from above example  Set##VarName  will convert into SetstrName .

Filed under: General 1 Comment