我目前使用以下模板作为检查NULL指针的方法,如果为NULL则将错误消息打印到日志文件然后返回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;
}
Run Code Online (Sandbox Code Playgroud)
我现在称之为:
if( !(isnull(dim, BOOST_STRINGIZE(dim))) ) return false;
Run Code Online (Sandbox Code Playgroud)
如果你注意到我需要将我要打印的指针变量的"名称"传递给日志文件,作为第二个参数.我目前正在使用BOOST_STRINGIZE,它只是将括号内的任何文本转换为字符串.
以下是我的模板实现的缺点(至少我的用法)
无论如何我可以自动确定第一个变量的"名称",这样我可以省略每次调用时将其作为第二个参数传入吗?
你可以将它全部放在一个宏中:
#define IS_NULL(name_) isnull(name_, #name_)
Run Code Online (Sandbox Code Playgroud)
注意,BOOST_STRINGIZE如果它是一个宏,可以扩展它的参数,这可能是你想要的,也可能不是你想要的:
#define X(x_) std::cout << BOOST_STRINGIZE(x_) << " = " << x_ << std::endl;
X(NULL); // prints: "0 = 0"
Run Code Online (Sandbox Code Playgroud)