On Friday, 8 December 2017 at 01:30:13 UTC, Manu wrote:

I tried this, and was surprised it didn't work:

int ctfeOnly(int x)
{
static assert(__ctfe);
return x + 1;
}

This would probably solve the problem in a satisfying way without an attribute?

Interestingly, if you put `__ctfe` in a function it does seem to work (unless I'm missing something). Check this out.

import std.stdio;

bool isRunTime()
{
    return !__ctfe;
}

bool isCompileTime()
{
    static if (!isRunTime())
        return __ctfe;
    else
        return false;
}

string onlyCompileTime()
{
    static assert(isCompileTime(),
        "This function can only be executed at compile time");
    assert(isCompileTime(),
        "This function can only be execute at compile time");
    return "onlyCompileTime";
}

string onlyRunTime()
{
    // This assert will actually throw an error at compile-time,
    // if an attempt is made to execute it at compile time.
assert(isRunTime(), "This function can only be executed at run time");
    return "onlyRunTime";
}

void main(string[] args)
{
    static assert(isCompileTime());
    static assert (!isRunTime());

    assert(!isCompileTime());
    assert(isRunTime());

    static assert(onlyCompileTime() == "onlyCompileTime");

    // Compile-time Error: Good!
    //static assert(onlyRunTime() == "onlyRunTime");

    assert(onlyRunTime() == "onlyRunTime");

    // Compile-time Error: Good!
    // pragma(msg, onlyRunTime());

    // I couldn't figure out how to force `onlyCompileTime` to
    // execute at runtime.  That's probably a good thing.
}

https://run.dlang.io/is/64fRRX

I guess this is due to the fact that wrapping `__ctfe` in a function causes it to run at compile-time instead of at...well...compile-time (i.e. https://wiki.dlang.org/User:Quickfur/Compile-time_vs._compile-time)

Mike

Reply via email to