我可以使用##
预处理程序指令将命名空间与类名连接吗?
我写了这个例子来展示我想要做的事情:
namespace ns {
class A
{
public:
void print(){ std::cout << "A" << std::endl; };
};
}
#define PRINT_NS(E) ([](){ ::ns::##E e; e.print(); }())
int main()
{
PRINT_NS(A);
}
它给出了以下编译错误:
13:30: error: pasting "::" and "A" does not give a valid preprocessing token
17:3: note: in expansion of macro 'PRINT_NS'
看起来::
未考虑##
之前的任何内容。
答案 0 :(得分:0)
在这种情况下,不需要粘贴任何东西,因为::
不是预处理器令牌,预处理器将能够替换E就好了(working example):
#define PRINT_NS(E) ([](){ ::ns::E e; e.print(); }())
当您想要粘合部件时,应使用 ##
,否则将被视为单个令牌,如下所示:
#define PRINT_NS(E) ([](){ ::ns::My_##E e; e.print(); }())