【发布时间】:2013-05-04 13:24:41
【问题描述】:
是否可以这样定义:
#define FOO(x, y) BAR()
#define FOO(x, sth, y) BAR(sth)
这样:
FOO("daf", sfdas);
FOO("fdsfs", something, 5);
翻译成这样:
BAR();
BAR(something);
?
编辑:
实际上,BAR 是我班级的方法。很抱歉之前没有这么说(认为这无关紧要)。
回答 DyP 的问题:
class Testy
{
public:
void TestFunction(std::string one, std::string two, std::string three)
{
std::cout << one << two << three;
}
void AnotherOne(std::string one)
{
std::cout << one;
}
void AnotherOne(void)
{
std::cout << "";
}
};
#define PP_NARG(...) PP_NARG_(__VA_ARGS__,PP_RSEQ_N())
#define PP_NARG_(...) PP_ARG_N(__VA_ARGS__)
#define PP_ARG_N(_1, _2, _3, N, ...) N
#define PP_RSEQ_N() 3, 2, 1, 0
// macro for exactly 2 arguments
#define FOO_2(_1, _2) AnotherOne()
// macro for exactly 3 arguments
#define FOO_3(_1, _2, _3) AnotherOne(_2)
// macro selection by number of arguments
#define FOO_(N) FOO_##N
#define FOO_EVAL(N) FOO_(N)
#define TestFunction(...) FOO_EVAL(PP_NARG(__VA_ARGS__))(__VA_ARGS__)
然后调用:
Testy testy;
testy.TestFunction("one", "two", "three"); // line 9
编译器输出:
警告 1 警告 C4003:宏 'PP_ARG_N' main.cpp 9 的实际参数不足
警告 2 警告 C4003:宏 'FOO_' main.cpp 9 的实际参数不足
错误 3 错误 C2039: 'FOO_' : is not a member of 'Testy' main.cpp 9
【问题讨论】:
-
可以让它分别扩展到
BAR(sfdas);和BAR(something, 5);。这可以接受吗?宏不能“丢弃”最后一个参数,但可以丢弃第一个参数。
标签: c++ macros c-preprocessor