[英]Is it possible to transform characters in a preprocessor directive?
问题很简单。 我希望宏MAKE_SUPER_VECTOR(type)
生成SuperVector<type>
的实例。 我希望该实例具有特定的名称。 因此,例如,如果我的类型是int
,我希望将其称为supervector_of_int_
。 问题是,如果我的类型稍微复杂一些(例如,名称空间中的类或某些模板类),那么我将无法创建此类实例。 为的情况下(在本例中) ns::C
,我想创建一个SuperVector<ns::C>
称为supervector_of_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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.