27 April, 2009

Using C++ Template to Create Debug Message

We usually use some macro to create debug message, likes: #define DEBUG_LOG(str) ....

I found out that we can use c++ template to achieve to same functionality. See the following code:

template<int T>
class Debug_Msg
{
public:
wstring str;
Debug_Msg( wstring s ):str(s){};
};

template<int T>
wostream& operator<<(wostream& wos, Debug_Msg<T> d);

template<>
wostream& operator<<(wostream& wos, Debug_Msg<0> d)
{
return wos;
}

template<>
wostream& operator<<(wostream& wos, Debug_Msg<1> d)
{
wos << d.str;
return wos;
}

To print out the debug message: 
wcout << Debug_Msg<1>("This is the debug message");

C++ template provides more flexible way to handle debug message.

1 comment:

Unknown said...

蠻有趣的~