December 31
Hello everyone,


I started to learn D a few weeks ago and have been stuck trying to solve the following problem :

- determine at compile time whether an alias is defined or not in a struct/class.

You'll find my attempt thereafter, something similar to how it's done in C++ (using the type void_t and partial specialization of a templated struct) :



alias void_t(T) = void;

struct define_default_type(T) {

    static struct test(U, V = void) {
        static const bool value = false;
    }

    static struct test(U, V : void_t!(U.default_type)) {
        static const bool value = true;
    }

    static const bool value = test!(T).value;
}

unittest {

    struct S {
        alias default_type = void;
    }

   assert(define_default_type!S.value); //define_default_type!S.value is false, not sure why
}



I can't tell what's wrong with the code above or if this is even the right way to go about it with D.

Would anyone have pointers to give me on how to solve this ?

Thanks a lot !

December 31
On 12/31/17 10:01 AM, ktoast wrote:
> Hello everyone,
> 
> 
> I started to learn D a few weeks ago and have been stuck trying to solve the following problem :
> 
> - determine at compile time whether an alias is defined or not in a struct/class.
> 
> You'll find my attempt thereafter, something similar to how it's done in C++ (using the type void_t and partial specialization of a templated struct) :
> 
> 
> 
> alias void_t(T) = void;
> 
> struct define_default_type(T) {
> 
>      static struct test(U, V = void) {
>          static const bool value = false;
>      }
> 
>      static struct test(U, V : void_t!(U.default_type)) {
>          static const bool value = true;
>      }
> 
>      static const bool value = test!(T).value;
> }
> 
> unittest {
> 
>      struct S {
>          alias default_type = void;
>      }
> 
>     assert(define_default_type!S.value); //define_default_type!S.value is false, not sure why
> }
> 
> 
> 
> I can't tell what's wrong with the code above or if this is even the right way to go about it with D.
> 
> Would anyone have pointers to give me on how to solve this ?
> 
> Thanks a lot !
> 

hm... what it looks like you are trying to do is find out if the struct has a member default_type, and if it is an alias to a type? It's hard to tell because of your C++-like attempt :)

This is how I would do it:

enum define_default_type(S) = is(S.default_type);

an isexpression has a lot of power: https://dlang.org/spec/expression.html#IsExpression

The default iexpression just returns true if the given symbol is a type.

So now:

assert(define_default_type!S);

or even better:

static assert(define_default_type!S); // check at compile-time

See if it fits your needs.

If it doesn't do quite what you want, there are a lot of goodies here: https://dlang.org/spec/traits.html

and here: https://dlang.org/phobos/std_traits.html

-Steve