Richard E
Richard E

Reputation: 3422

Preprocessing: Is defining a shorthand for `import` legal?

For solving a code-golf challenge, I want to produce the smallest possible code. I had the idea of defining a shorthand for import:

#define I import
I<vector>;

short godbolt example

Of course, the intention here is to reuse I to actually save bytes.

Is this legal in C++20?

Thoughts / What I found out so far:

Upvotes: 4

Views: 199

Answers (1)

T.C.
T.C.

Reputation: 137365

No.

[cpp.pre]/1:

A preprocessing directive consists of a sequence of preprocessing tokens that satisfies the following constraints: At the start of translation phase 4, the first token in the sequence, referred to as a directive-introducing token, begins with the first character in the source file (optionally after whitespace containing no new-line characters) or follows whitespace containing at least one new-line character, and is [...]

Preprocessing-directive-ness is determined at the start of translation phase 4, prior to any macro replacement. Therefore, I<vector>; is not recognized as a directive, and the import from the macro expansion of I is not replaced by the import-keyword token. This in turn means that it is not recognized as a module-import-declaration during translation phase 7, and is instead simply an ill-formed attempt to use the identifier import without a preceding declaration.

The point of this dance is to ensure that build systems can know a file's dependencies without having to fully preprocess the file - which would be required if imports can be formed from macro replacement.

Upvotes: 11

Related Questions