用于命名空间限定的c++预处理器令牌粘贴
C++ preprocessor token pasting for namespace qualification
我在gcc 4.7.1 (std=c++11)中使用预处理器令牌粘贴操作符时遇到了麻烦。也就是说,考虑以下代码:
// Create a name for a global map (this works)
#define GLOBAL_MAP(name) g_map_ ## name // This works fine
// Now, namespace qualify this map (this fails to compile when used)
#define NS_QUAL_GLOBAL_MAP(name) SomeNamespace:: ## GLOBAL_MAP(name)
使用场景-首先是映射定义:
std::map<std::string,std::string> GLOBAL_MAP(my_map);
namespace SomeNamespace
{
std::map<std::string,std::string> GLOBAL_MAP(my_map);
}
用法:
void foo()
{
bar(GLOBAL_MAP(my_map)); // This compiles fine
baz(NS_QUAL_GLOBAL_MAP(my_map)); // This fails to compile with:
// error: pasting "::" and "NAME_MAP" does not give a
// valid preprocessing token
}
我认为可能发生的情况是,它将GLOBAL_MAP
解释为##
之后的标记,而不是要进一步扩展的宏。我该怎么解决这个问题?
标记粘贴生成一个单个标记供编译器读取。这不是你想要的- ::
本身是一个有效的c++令牌,但::g_map_my_map
不是编译器知道的令牌。
因此,删除令牌粘贴操作符:
#define NS_QUAL_GLOBAL_MAP(type) SomeNamespace::GLOBAL_MAP(type)
在::
之后不需要##
操作符。##
运算符用于形成单个令牌,但SomeNamespace::g_map_mymap
无论如何都是多个令牌。只做
#define NS_QUAL_GLOBAL_MAP(type) SomeNamespace::GLOBAL_MAP(type)
你只需要SomeNamespace:: GLOBAL_MAP(name)
。
您不能将g_map_my_map
这样的名称加入::
令牌,因为::g_map_my_map
不是一个有效的令牌,它是两个令牌。所以把它们放在一起就行了,不要把它们连在一起
相关文章:
- 如何在C++中使用X509证书模在令牌中查找私钥
- holeMenuProgram.cpp:38:1 错误:'}'令牌之前的预期主表达式
- C++:"("令牌"之前有预期的非限定 id 指向类中成员函数的指针
- Arduino 用于语句错误。令牌之前的预期')' ';'。如何解决这个问题?
- 错误:令牌 { '{' 之前应存在非限定 ID
- 允许哪些令牌作为 #include 的参数?
- "错误 C0000:语法错误,令牌"<EOF>"处出现意外$end,并且不确定
- 它在 { 令牌之前给了我预期的标识符
- (错误:令牌之前'<<'预期的主表达式)
- 为什么 ## aka 令牌粘贴运算符不适用于 C 和 C++ 中的注释?
- 错误:"->"令牌之前的预期初始值设定项
- LINUX 操作系统上的错误:令牌之前预期的构造函数、析构函数或类型转换'('?
- 宏定义中的预处理器令牌两边有两个双引号
- 是否可以在多行字符串文本中使用 C/C++ 预处理器令牌
- 如何将字符串作为预处理器令牌传递
- C++预处理器能否判断令牌是否为字符串
- 用于命名空间限定的c++预处理器令牌粘贴
- 如何根据预定义的宏(C++预处理器)组成有效的令牌
- 正在确定预处理器令牌的值
- 令牌化时强制预处理器评估