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:
import directive should happen in translation phase 4, and for the whole phase, I should not be macro-expanded unless specified otherwise ([cpp.pre]-7). Is it specified otherwise for this case?include instead of import, does not work with gcc and clang and thus probably isn't legal.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With