是否有可能定義是這樣的:宏超載
#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的主要不夠的實際參數。 cpp 9
警告2警告C4003:不夠實際參數宏 'FOO_' 的main.cpp 9
錯誤3錯誤C2039: 'FOO_':不是 '暴躁' 的main.cpp 9
爲什麼使用宏? – 0x499602D2 2013-05-04 13:26:16
可以分別擴展到「BAR(sfdas)」和「BAR(something,5);」。這可以接受嗎?宏不能「放棄」最後一個參數,但可以放棄第一個參數。 – leemes 2013-05-04 13:29:49
另請參閱http://stackoverflow.com/questions/3850421/can-i-define-variadic-c-preprocessor-macros-with-va-args-in-the-middle-instead – leemes 2013-05-04 13:31:36