2011-10-23 95 views
14

可以在#define中使用双冒号吗?我想在实现文件中保存一些文字,例如像这样:在#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.

+0

好的问的问题,但我会发布你得到的语法错误 –

+5

这看起来对我来说是一个真正糟糕的主意,即使它工作(感谢上帝它没有)。没有人会理解或维护您的代码。你的继任者会坚持你的肖像。 – TonyK

回答

16

号宏的名称必须是一个标识符;它不能包含其他字符,也不能包含多个令牌。

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

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