I currently use the following template simply as a way to check for NULL pointer and if NULL then print out an error message to a log file and then return false.
template< typename T >
static bool isnull(T * t, std::string name = "")
{
_ASSERTE( t != 0 );
if( !t )
{
if( !(name.length()) ) name = "pointer";
PANTHEIOS_TRACE_ERROR(name + " is NULL");
return false;
}
return true;
}
I currently call this as follows:
if( !(isnull(dim, BOOST_STRINGIZE(dim))) ) return false;
If you notice I need to pass in the “name” of the pointer-variable that I want to print to the log file, as the 2nd parameter. I am currently using BOOST_STRINGIZE that simply converts any text inside the parentheses to a string.
The following are the disadvantages of my template implementation (for my usage at least)
- Anyone could pass in anything as parameter to BOOST_STRINGIZE to print out in log file – since the 2 parameters are not related in anyway – so I would not necessarily see the “variable name” that is actually NULL
- We have to remember to pass in the 2nd parameter, else useless.
Is there anyway I can have the “name” of that 1st variable be automatically determined, so that I can omit passing it in, as the 2nd parameter, with every call?
You could put it all in one macro:
Note that
BOOST_STRINGIZEexpands its argument if its a macro, which may or may not be what you want: