Metafunctions
Overview
A metafunction is a compile-time function that can participate in interpreting the meaning of a declaration, and can:
-
apply defaults (e.g.,
interfacemakes functions virtual by default) -
enforce constraints (e.g.,
valueenforces that the type has no virtual functions) -
generate additional functions and other code (e.g.,
valuegenerates copy/move/comparison operations for a type if it didn't write them explicitly)
The most important thing about metafunctions is that they are not hardwired language features — they are compile-time library code that uses the reflection and code generation API, that lets the author of an ordinary type easily opt into a named set of defaults, requirements, and generated contents. This approach is essential to making the language simpler, because it lets us avoid hardwiring special "extra" types into the language and compiler.
Applying metafunctions using @
Metafunctions provide an easy way for a type author to opt into a group of defaults, constraints, and generated functions: Just write @name afer the : of a declaration, where name is the name of the metafunction. This lets the type author declare (and the human reader see) the intent up front: "This isn't just any type, this is a @value type" which automatically gives the type default/copy/move construction and assignment, <=> with std::strong_ordering comparisons, and guarantees that it has a public destructor and no protected or virtual functions:
point2d: @value type = {
x: i32 = 0;
y: i32 = 0;
// @value automatically generates default/copy/move
// construction/assignment and <=> strong_ordering comparison,
// and emits an error if you try to write a non-public
// destructor or any protected or virtual function
}
Generating source code at compile time
A metafunction applied to a definition using @ gets to participate in interpreting the meaning of the definition by inspecting and manipulating the definition's parse tree. For example:
shape: @interface @print type = {
draw : (this);
move_by: (this, dx: double, dy: double);
}
The above code:
-
applies
@interface, which makes functions pure virtual by default and defines a virtual destructor with a do-nothing body if there isn't already a virtual destructor (among other things), and -
then applies
@print, which pretty-prints the resulting parse tree as source code to the console so that we can see the results of what the first metafunction did.
The result of compiling this is the following cppfront output, which is the @interface-modified Cpp2 source code as printed by @print: