www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Classes and CTFE

reply Andrea Fontana <nospam example.com> writes:
I used to think that classes can't be used with CTFE.

Instead it appears to work, if they're not directly returned but, 
for example, they're wrapped inside a struct as on example [1]. 
Ctor is called *only* at compile time, and instance works fine.

So, I can't understand: why wrapping a class inside a struct make 
it works?


Ex: http://dpaste.dzfl.pl/5879511dff02
Mar 10 2016
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Thursday, 10 March 2016 at 13:56:18 UTC, Andrea Fontana wrote:
 I used to think that classes can't be used with CTFE.
Classes have worked normally with CTFE for several years now. You don't need to do anything special with them.
 Ex: http://dpaste.dzfl.pl/5879511dff02
This just doesn't do what you think it does: if (__ctfe) pragma(msg, "compile-time"); That will ALWAYS print the thing because if(__ctfe) is a *run time* branch, and pragma(msg) is a compile time thing. The code gets compiled, even if __ctfe == false, so it will print anyway. enum forceCTFE(alias expr)=expr; That's only one way to do CTFE. Notice the error message: variable p.forceCTFE!(willnot).forceCTFE : Unable to initialize enum with class or pointer to struct. Use static const variable instead. enums don't work in references, so you do a static variable instead. Static variables are still CTFE'd.
Mar 10 2016
parent Andrea Fontana <nospam example.com> writes:
On Thursday, 10 March 2016 at 14:36:18 UTC, Adam D. Ruppe wrote:
 On Thursday, 10 March 2016 at 13:56:18 UTC, Andrea Fontana 
 wrote:
 I used to think that classes can't be used with CTFE.
Classes have worked normally with CTFE for several years now. You don't need to do anything special with them.
 Ex: http://dpaste.dzfl.pl/5879511dff02
This just doesn't do what you think it does: if (__ctfe) pragma(msg, "compile-time"); That will ALWAYS print the thing because if(__ctfe) is a *run time* branch, and pragma(msg) is a compile time thing. The code gets compiled, even if __ctfe == false, so it will print anyway.
Yes but in one case it will print only that message, if instanced at runtime it will print the other too. I was just verifing if ctor was called correctly (in a more complex code)
 enum forceCTFE(alias expr)=expr;


 That's only one way to do CTFE.
I just wanted to be sure it is ctfe.
 Notice the error message:

 variable p.forceCTFE!(willnot).forceCTFE : Unable to initialize 
 enum with class or pointer to struct. Use static const variable 
 instead.



 enums don't work in references, so you do a static variable 
 instead. Static variables are still CTFE'd.
So problem is actually enum, not ctfe. Nice. Thank you :)
Mar 10 2016