带有可变参数的C ++宏

时间:2014-03-19 03:14:01

标签: c++ variadic-macros

1。#define debug(...) printf( __VA_ARGS__)

2. #define debug(...) std::cout<< __VA_ARGS__

显然,1表示正常,2编译时会出错。 是否有可能使用&#34; std :: cout&#34;变量参数?

这个宏的重点是什么?

&#39;调试&#39;宏用于打印一些东西来调试代码。

void test(const classtype1 &obj1,const classtype2 &obj2)
{
    // rewrite operator<< 
    debug(obj1,obj2); 

    //if use printf, I must call tostring method(or something likes that) to 
    //series the object to string. 
    debug(obj1.tostring(),obj2.tostring());   

    ...
}

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

#define DEBUG(x) do { std::osacquire( std::cerr ) << __FILE__ << ":" << __LINE__ << " " << x << std::endl; } while (0);

然后在任何要使用宏的地方:

DEBUG( obj1.tostring() + " some stuff " + obj2.tostring() )
相关问题