Pass the variable "name" in C ++

I am currently using the following pattern simply as a way to check for a NULL pointer, and if NULL then prints an error message in the log file and then returns 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 am currently invoking this as follows:

 if( !(isnull(dim, BOOST_STRINGIZE(dim))) ) return false; 

If you notice that I need to pass the "name" of the variable pointer that I want to print in the log file as the second parameter. I am currently using BOOST_STRINGIZE, which simply converts any text in parentheses to a string.

The disadvantages of my template implementation are listed below (at least for my use)

  • Anyone can pass something as a BOOST_STRINGIZE parameter for printing in a log file - since all two parameters are not related to each other, so I will not necessarily see a "variable name", which is actually NULL
  • We must remember to pass the second parameter, otherwise useless.

Anyway, can I define the "name" of this 1st variable so that I can skip it as a second parameter with every call?

+6
c ++
source share
3 answers

You can put it all in one macro:

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

Note that BOOST_STRINGIZE expands its argument if its 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" 
+9
source share

Of course, why not:

 #define new_isnull(x) isnull(x, BOOST_STRINGIZE(x)) 
+1
source share

The only way to do things lexically in this way is through macros. If you always want to get the correct listing, the best option is to wrap the entire statement with 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.

+1
source share

All Articles