Trait for "can be instantiated"?
    ag0aep6g 
    anonymous at example.com
       
    Tue May 10 05:45:25 UTC 2022
    
    
  
On 09.05.22 23:24, Ben Jones wrote:
> enum x;
> enum y = 5;
> 
> struct Wrap(alias T) {
>      static if(isType!T){
>           T value; //When t == x this doesn't work because `x` is opaque 
> and has no default initializer
>      }
> }
[...]
> 
> x is a "type" as far as isType is concerned (which makes sense to me), 
> but I don't think you can ever declare a variable of that type since 
> there's no way to initialize it... Is there a trait that can tell if you 
> can initialize a variable of a certain type?  The best I can think of is 
> __traits(compiles, "T x;"), but it seems like it should be possible to 
> do better?
`x` is a type, period.
You can use void initialization to declare values of types that don't 
have an `init` value: `x value = void;`
As for an alternative to the brute force `__traits(compiles, ...)`, you 
can check if `T.init` is a thing:
     static if (is(typeof(T.init))) { T value; }
I'm not sure if that's really better, though.
By the way, what is your `Wrap` supposed to do with `x`? Treating it 
like `y` will likely fail, too, because `x` is not a value.
    
    
More information about the Digitalmars-d-learn
mailing list