Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable "name" in C++

Tags:

c++

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?

like image 697
ossandcad Avatar asked Feb 24 '10 19:02

ossandcad


2 Answers

You could put it all in one macro:

#define IS_NULL(name_) isnull(name_, #name_)

Note that BOOST_STRINGIZE expands its argument if its a macro, which may or may not be what you want:

#define X(x_) std::cout << BOOST_STRINGIZE(x_) << " = " << x_ << std::endl;
X(NULL); // prints: "0 = 0"
like image 64
Georg Fritzsche Avatar answered Sep 24 '22 03:09

Georg Fritzsche


The only way to do anything lexically like this is with macros. If you always want the correct printout, your best option is to wrap the whole statement in a macro:

//if( !(isnull(dim, BOOST_STRINGIZE(dim))) ) return false;
#define ISNULL(a) isnull((a), #a)
if (!ISNULL(dim)) return false;

Note that, as always, macros have a number of disadvantages associated with them.

like image 37
Dan Olson Avatar answered Sep 22 '22 03:09

Dan Olson