c++ - 在#define 中使用双冒号 (::)

标签 c++ compiler-errors c-preprocessor

我可以在 #define 中使用双冒号吗?我想在实现文件中保存一些文字,例如像这样:

// foo.h
#define template template <class T>
#define foo:: foo<T>::

template class foo {
  T& baz();
};

#include "foo.tpp"
#undef template
#undef foo::

// foo.tpp
template T& foo::baz() {
    // do stuff.
}

但是我遇到了我不太理解的语法错误。 (参见 codepad 上的示例):

Line 11: error: missing whitespace after the macro name
Line 10: error: extra tokens at end of #undef directive
Line 4: error: 'foo' is not a template
compilation terminated due to -Wfatal-errors.

最佳答案

没有。宏的名称必须是标识符;它不能由其他字符组成,也不能由多个标记组成。

#define template无效,因为 template不是标识符,而是关键字。

#define foo:: foo<T>::在 C90 和 C++98 中有效:它定义了一个名为 foo 的宏替换为 :: foo<T>:: (这不是您想要做的,但它是有效)。但是,这在 C99 和 C++11 中是无效的,因为在这些语言的较新版本中,类对象宏的名称与其替换列表(替换它的标记)之间必须有空格。

关于c++ - 在#define 中使用双冒号 (::),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7863467/

相关文章:

c - 使用 C 预处理器宏进行多级调试

c++ - gcc 的任何标签来编译包含 C 3rd 方头文件的 Cpp 文件

c++ - urdl 编译错误

c++ - 无法在 DirectX11 上创建一维纹理

c - 为什么我在 C 程序中收到杂散 '342' 错误?

methods - F#编译器需要项目引用,但方法是私有(private)的

c - 宏名称的有效字符是什么?

c++ - 如何在 C 宏中使用#if,#else,#endif...

c++ - 如何调用返回 double 或字符串并将其保存在 map 上但作为对象的类的方法

c++ - 抽象类的模板实例化