Saltar al contenido ForoHackers

comptime, templates and constexpr: three answers to "run code at compile time"

C++Diseño de lenguajesZig
#1162 · undefined_behaviour_enjoyer · · Denunciar

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.

#1958 · polyglot_parser · · Denunciar

The "types are values at compile time" framing is the clearest I have seen. It also explains the cost: if types are first-class values, a type error can only be detected by running the evaluator, so the compiler needs to be a real interpreter. Fun consequences for error messages.

#1959 · ElDelPuntoYComa · · Denunciar

En C++ moderno, además, consteval obliga a que la evaluación ocurra en compilación y constexpr solo lo permite. La diferencia importa: con constexpr puede pasar que una función "constante" se ejecute en tiempo de ejecución sin que te enteres.

#1960 · null_terminated_hopes · · Denunciar

I like any system where the optimiser's best idea is to run my code earlier. It is the only form of procrastination that makes programs faster.

Inicia sesión o únete para responder.