【发布时间】:2015-03-30 05:33:03
【问题描述】:
我发现使用 C 风格的宏和使用 C++11 中引入的新的统一列表初始化形式之间似乎不兼容,但这种事情绝对不可能编写出来,这似乎令人难以置信,所以我认为我遗漏了一些东西。
这是问题所在:当预处理器查找宏参数时,大括号似乎被忽略了。像 MACR(Range{2,4}) 这样的调用被误解为有两个参数,Range{2 和 4。在下面的代码中,一切都很好(嗯,风格很差,但它有效),直到标记的行:
#include <iostream>
using namespace std;
struct Range { int st, fn; };
ostream& operator << (ostream& out, const Range& r)
{ return out << "(" << r.st << "," << r.fn << ")"; }
#define COUT(X) (cout << (X) << endl)
int main()
{
COUT(3);
Range r {3,5};
COUT(r);
COUT(Range{3,5}); //this line won't compile
}
它给出以下错误消息:
badmacro.cpp:16:18: error: macro "COUT" passed 2 arguments, but takes just 1
COUT(Range{3,5});
^
compilation terminated due to -Wfatal-errors.
尤其是在使用较旧的库时,有时不可避免地会使用宏调用;在这些情况下,我们肯定不应该放弃新语法吗?有官方的解决方法吗?
【问题讨论】:
标签: c++11 c-preprocessor