How to ensure template function can be processed during compile time

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Jul 8 20:29:06 UTC 2020


On Wed, Jul 08, 2020 at 08:11:05PM +0000, IGotD- via Digitalmars-d-learn wrote:
[...]
> Doing the same in D, would with my lack of knowledge look like this.
> 
> 
> size_t mySize(T)()
> {
>     return T.sizeof + 42;
> }

What you want is:

	enum mySize(T) = T.sizeof + 42;

And there is no need for a const overload.


[...]
> 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

Yes, because you're trying to pass the value of a variable to mySize,
and that variable doesn't have a value until runtime.


> Here we have a difference between C++ and D as C++ was able infer the
> size of v during compile time.
> 
> Now since mySize is a template, shouldn't this work mySize!v, but it
> doesn't? What essential understanding have I missed here?

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


T

-- 
The diminished 7th chord is the most flexible and fear-instilling chord.
Use it often, use it unsparingly, to subdue your listeners into
submission!


More information about the Digitalmars-d-learn mailing list