Compile time opAssign/@property constraints

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Jan 5 01:38:43 UTC 2019


On Friday, January 4, 2019 4:50:30 AM MST Jacob Shtokolov via Digitalmars-d-
learn wrote:
> On Friday, 4 January 2019 at 11:41:59 UTC, Simen Kjærås wrote:
> > The thing is, compile-time tests like static if and static
> > assert can only test values that are known at compile-time, and
> > are for the most part useful only in templates.
>
> Thanks for this answer! That's sad to hear.
> But, is there anything to do with CTFE? Can it help somehow in
> such situation?

CTFE is the compile-time evaluation of functions. You're calling a function
at compile time. How the function works is basically the same as how it
works at runtime. There are some caveats because of how the CTFE engine
works (e.g. pointer arithmetic isn't legal at compile time), but the
function itself is called normally. Something like a static assertion is run
when the function itself is compiled - which must happen before that
function is used during CTFE. So, you can do something like

auto foo(int i)
{
    static assert(someFunc() == 42);
    ...
}

but you can't do something like

auto foo(int i)
{
    static assert(someFunc() == i);
    ...
}

because that would be mixing compile time and runtime stuff. Even if foo is
called at compile time, it's compiled before it's called, and the static
assertion is part of its compilation process, not part of running it, and
runtime variables aren't available when the function is being compiled. So,
if you did

auto foo(int i)
{
    assert(someFunc() == i);
    ...
}

and then called foo with CTFE, then that assertion would be run as part of
running foo just like it would be at runtime, but a static assertion
wouldn't make sense. CTFE doesn't fundamentally change what is a
compile-time and what is a runtime constructs. It just allows functions to
be called at compile time so that you can do stuff like initialize values
that are generated at compile time.

Unfortunately, the wiki seems  be down right now, but once it's back up, I
suggest that you read

https://wiki.dlang.org/User:Quickfur/Compile-time_vs._compile-time

IIRC, it's still a work in progress, but it should give you a much clearer
idea of how CTFE fits into things.

- Jonathan M Davis






More information about the Digitalmars-d-learn mailing list