【问题标题】:C++ macro with variable arguments带有可变参数的 C++ 宏
【发布时间】:2014-03-19 03:14:00
【问题描述】:

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

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

显然,1 是可以的,2 会在编译时出错。 是否有可能将“std::cout”与可变参数一起使用?

这个宏有什么意义?

'debug' 宏用于打印调试代码。

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());   

    ...
}

【问题讨论】:

  • 这个宏有什么意义?
  • 为了做到这一点,你需要 C++11,而在那个时候,你到底为什么要选择它而不是可变参数模板?
  • 如果您使用 C,请使用 printf。如果您使用的是 c++,请不要使用宏。即使你需要使用 va_args,你为什么要使用宏?
  • 因为我想知道调用宏“debug”的函数名,可变参数模板能做到吗?
  • 首先你使用的是什么编译器?不同的编译器对可变参数宏的处理方式不同。

标签: c++ variadic-macros


【解决方案1】:

你可以这样做:

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

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

DEBUG( obj1.tostring() + " some stuff " + obj2.tostring() )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-09
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    相关资源
    最近更新 更多