New to D and mimicking C++ : how to implement std::integral_constant<>?

Picaud Vincent via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 7 10:42:37 PST 2016


Hi all,

I have ~15y of C++ and now I want to test D, because it seems 
really intersting and "cleaner" than C++.

As an exercice I m trying to implement something equivalent to 
the C++ std::integral_constant<T,T value> in D.

In D:

struct IntegralConstant(T, T VALUE) {
  ...
}

But I do not know how to write a compile-time type check. I tried

template isIntegralConstant(ANY)
{
     enum bool 
isIntegralConstant=__traits(identifier,ANY)=="IntegralConstant";
}

But when using it with ANY=long type, I get a compile-time error:

"argument long has no identifier"

A workaround that worked is:

struct IntegralConstantTag {}

struct IntegralConstant(T, T VALUE) {
   private IntegralConstantTag selfTag_;
   alias selfTag_ this;
}

template isIntegralConstant(ANY)
{
     enum bool isIntegralConstant=is(ANY : IntegralConstantTag);
}

But now I'm sticked by a compiler issue when I want to introduce 
2 "alias this" to allow implicit conversion:

struct IntegralConstant(T, T VALUE) {
   private IntegralConstantTag selfTag_;
   alias selfTag_ this;
   T value_=VALUE;
   alias value_ this;
}

Compiler error message is "integralConstant.d:16:3: error: there 
can be only one alias this".


I would be very graceful for any help/advice that explains the 
right way to implement C++ std::integral_constant<T,T value> in 
the D language.

Vincent



More information about the Digitalmars-d-learn mailing list