Use double colons (::) in #define

2019-02-21 08:55发布

问题:

May I use double colons in #define ? I'd like to save some writing in the implementation files, e.g. like this:

// 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.
}

But I get syntax errors I don't really understand. (See an example on 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.

回答1:

No. The name of a macro must be an identifier; it can't consist of other characters and it can't consist of multiple tokens.

#define template is invalid because template is not an identifier, it is a keyword.

#define foo:: foo<T>:: was valid in C90 and C++98: it defines a macro named foo that is replaced by :: foo<T>:: (that's not what you want to do, but it was valid). However, this is invalid in C99 and C++11 because in the newer revisions of the languages, there must be whitespace between the name of an object-like macro and its replacement list (the tokens with which it is replaced).