是否可以转换预处理器指令中的字符?

Is it possible to transform characters in a preprocessor directive?

本文关键字:字符 指令 处理器 转换 预处理 是否      更新时间:2023-10-16

问题很简单。我希望宏MAKE_SUPER_VECTOR(type)生成SuperVector<type>的实例。我希望此实例具有特定名称。例如,如果我的类型是int,我希望它被称为supervector_of_int_。问题是,如果我的类型稍微复杂一些,例如,命名空间中的类或某个模板类,我就无法创建这样的实例。对于ns::C的情况(在示例中(,我想创建一个名为supervector_of_ns__C_SuperVector<ns::C>。使用std::vector<int>作为我的类型的情况对我来说并不那么重要,但很高兴知道。

我试图让它尽可能简单。假设宏GET_SUPER_VECTOR很重要且无法擦除。

#include <iostream>
#include <vector>
template<typename T>
class SuperVector : public std::vector<T> {
// Whatever...
};
namespace ns {
class C {
int x;
};
}
#define GET_SUPER_VECTOR(type) supervector_of_ ## type ## _
#define MAKE_SUPER_VECTOR(type) SuperVector<type> GET_SUPER_VECTOR(type)
MAKE_SUPER_VECTOR(int);
MAKE_SUPER_VECTOR(ns::C);
MAKE_SUPER_VECTOR(std::vector<int>);
int main() {
}

这是我收到的错误消息:

program.cc:17:34: error: pasting ">" and "_" does not give a valid preprocessing token
MAKE_SUPER_VECTOR(std::vector<int>);
^
program.cc:13:51: note: in definition of macro ‘GET_SUPER_VECTOR’
#define GET_SUPER_VECTOR(type) supervector_of_ ## type ## _
^~~~
program.cc:17:1: note: in expansion of macro ‘MAKE_SUPER_VECTOR’
MAKE_SUPER_VECTOR(std::vector<int>);
^~~~~~~~~~~~~~~~~
program.cc:13:32: error: ‘supervector_of_ns’ has not been declared
#define GET_SUPER_VECTOR(type) supervector_of_ ## type ## _
^
program.cc:14:51: note: in expansion of macro ‘GET_SUPER_VECTOR’
#define MAKE_SUPER_VECTOR(type) SuperVector<type> GET_SUPER_VECTOR(type)
^~~~~~~~~~~~~~~~
program.cc:16:1: note: in expansion of macro ‘MAKE_SUPER_VECTOR’
MAKE_SUPER_VECTOR(ns::C);
^~~~~~~~~~~~~~~~~
program.cc:13:32: error: ‘supervector_of_std’ has not been declared
#define GET_SUPER_VECTOR(type) supervector_of_ ## type ## _
^
program.cc:14:51: note: in expansion of macro ‘GET_SUPER_VECTOR’
#define MAKE_SUPER_VECTOR(type) SuperVector<type> GET_SUPER_VECTOR(type)
^~~~~~~~~~~~~~~~
program.cc:17:1: note: in expansion of macro ‘MAKE_SUPER_VECTOR’
MAKE_SUPER_VECTOR(std::vector<int>);
^~~~~~~~~~~~~~~~~
program.cc:17:30: error: expected initializer before ‘<’ token
MAKE_SUPER_VECTOR(std::vector<int>);
^
program.cc:13:51: note: in definition of macro ‘GET_SUPER_VECTOR’
#define GET_SUPER_VECTOR(type) supervector_of_ ## type ## _
^~~~
program.cc:17:1: note: in expansion of macro ‘MAKE_SUPER_VECTOR’
MAKE_SUPER_VECTOR(std::vector<int>);

宏粘贴的结果必须是有效的标识符。

supervector_of_std::vector<int>不是有效的标识符。

您可以为宏指定第二个参数来表示针尖识别器,例如:

#define MAKE_SUPER_VECTOR(type, identname ) SuperVector<type> GET_SUPER_VECTOR(identname)

然后这样称呼它:MAKE_SUPER_VECTOR( std::vector<int>, std_vector_int );