How to ensure template function can be processed during compile time

Stanislav Blinov stanislav.blinov at gmail.com
Wed Jul 8 21:12:23 UTC 2020


On Wednesday, 8 July 2020 at 20:11:05 UTC, IGotD- wrote:

> int v;
>
> enum sz = mySize!int // works, returns 46
> enum sz2 = mySize(v) // doesn't work. Error: variable v cannot 
> be read at compile time
>
> Here we have a difference between C++ and D as C++ was able 
> infer the size of v during compile time.

To add to other respondents' replies, you can pass something that 
is known at compile time, for example the .init value:

int v;
enum sz2 = mySize(v.init);
static assert(sz2 == 46);

This way the compiler is able to evaluate `mySize` at compile 
time.

Or use an alias template argument:

auto mySize(alias v)()
{
     return v.sizeof + 42;
}

int v;
enum sz = mySize!int;
enum sz2 = mySize!v;
static assert(sz == sz2);
static assert(sz == 46);


More information about the Digitalmars-d-learn mailing list