我在 StackOverflow 上阅读了不同的相关答案,但没有一个能给我这个问题的答案。我需要连接传递给宏的实体(不一定是字符串),它们之间有一个分隔符(在我的例子中是点)。这是我的代码:
#define STR(x) #x
#define XSTR(x) STR(x)
#define CONC_(a, b) a ## b
#define CONC(a, b) CONC_(a, b)
#define CONC3(_1, _2, _3, S) CONC2(CONC2(_1, _2, S), _3, S)
#define CONC2(_1, _2, S) CONC(_1, CONC(S, _2))
#define JOIN_UNDERSCORE(_1, _2, _3) XSTR(CONC3(_1, _2, _3, _))
#define JOIN_DOT(_1, _2, _3) XSTR(CONC3(_1, _2, _3, .)) // here I pass dot
这是您如何使用它的方法
std::string underscore = JOIN_UNDERSCORE(one, two, three);
std::string dot = JOIN_DOT(one, two, three); // this one doesn't compile
我可以使用另一种技术来实现这一点。喜欢:
#define APPEND_DOT(x) "." STR(x)
#define CONCSTR3(_1, _2, _3) CONCSTR2(_1, _2) APPEND_DOT(_3)
#define CONCSTR2(_1, _2) STR(_1) APPEND_DOT(_2)
#define CONCSTR1(_1) STR(_1)
#define JOIN_STR_DOT(_1, _2, _3) CONCSTR3(_1, _2, _3)
std::string dot_str = JOIN_STR_DOT(one, two, three);
这将适用于点。但问题是如何通过分隔符使其通用。
这是一个可以玩的链接https://godbolt.org/z/MDxsJS