c++ - 是否可以连接可变参数宏的参数以形成变量名?

标签 c++ c++17 string-concatenation variadic-macros

我正在尝试实现如下目标:

#define def_name(delim, ...) ??? // how will this variadic macro concatenate its parameters to define a new variable?

// Calling `def_name` as follows should define a new variable.

def_name("_", "abc", "def", "ghi");

// The following code should be generated after invoking the above macro.

inline constexpr char const abc_def_ghi_name[]{"abc_def_ghi"};

// Invoking the macro as:

def_name("", "abc", "def", "ghi");

// should produce the following code:

inline constexpr char const abcdefghi_name[]{"abcdefghi"};

def_name 宏应该是什么来支持上述用例?另外,可以使用 C++ templates/constexpr 在编译时实现类似的效果吗?

最佳答案

几乎没有语法变化(MACRO 可以字符串化,但不能取消字符串化),您的用法可能是:

def_name(, a, b)
def_name(_, a, b, c)

你可能会这样做,但有一些上限:

#define def_name1(sep, p1) \
    inline constexpr char const p1##_name[]{#p1};
#define def_name2(sep, p1, p2) \
    inline constexpr char const p1##sep##p2##_name[]{#p1 #sep #p2};
#define def_name3(sep, p1, p2, p3) \
    inline constexpr char const p1##sep##p2##sep##p3##_name[]{#p1 #sep #p2 #sep #p3};
// ...

为了调度到正确的地方,一些实用程序:

#define COUNT_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...)    N
#define COUNT(...)   COUNT_N(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
// Warning: COUNT() return 1 (as COUNT(A)) :-/

#define IDENTITY(N) N
#define APPLY(macro, ...) IDENTITY(macro(__VA_ARGS__))

最后

#define DISPATCH(N) def_name ## N
#define def_name(sep, ...) IDENTITY(APPLY(DISPATCH, COUNT(__VA_ARGS__)))(sep, __VA_ARGS__)

Demo

关于c++ - 是否可以连接可变参数宏的参数以形成变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69968476/

相关文章:

python - 在 Python 3 中使用字符串格式而不是字符串连接是否更 Pythonic?

java - 以下声明的差异

c++ - std::optional 值的地址是否稳定?

c++ - 我得到断言失败 "file_name != nullptr"但仅在 Release模式下

c++ - 动态可转换类型特征

c# - 我应该如何连接字符串?

c++ - 在其他模板中使用 Any 类(类似于 boost::any)

c++ - 如何获取类内部的结构?

java - 使用 C++ (JNI) 包装 Java 库

c++ - 如果要使用没有更新编译器的新功能该怎么办?