Three languages, three different answers to the same wish: do some computation before the program runs.
C++ templates. A separate sublanguage, functional, evaluated by the compiler by pattern matching on types. Powerful, and the error messages look like a stack trace of a very confused compiler.
C++ constexpr. Ordinary-looking functions that may be evaluated at compile time if all inputs are constants. The same function runs at compile time and at run time. Much better, but it still lives next to the template system, so you have two tools.
Zig comptime. One idea: any expression can be evaluated at compile time, using the same language, and types are values in that phase. A generic type is just a function that takes types and returns a type:
fn Matrix(comptime T: type, comptime n: usize) type {
return struct {
data: [n][n]T,
pub fn identity() @This() {
var m: @This() = undefined;
for (0..n) |i| {
for (0..n) |j| {
m.data[i][j] = if (i == j) 1 else 0;
}
}
return m;
}
};
}
const M3 = Matrix(f32, 3);
No angle brackets, no special syntax for "meta" code. comptime loops, comptime branches, the same standard library.
What does it cost? Less tooling for type-level tricks that C++ metaprogramming experts love, and the flexibility means compile-time evaluation can still go wrong in new and exciting ways. I do not think one is "better". I think the second two are what you get when you start from "what if the compiler is just an interpreter for the same language", and that idea is very easy to love.