Template return values?

Jacob Carlborg doob at me.com
Tue Dec 4 04:08:04 PST 2012


On 2012-12-04 08:48, Era Scarecrow wrote:
>   A thought's been going through my head for a while now. I wonder about
> template return values. Function signatures are usually the inputs and
> NOT the return type. However for writing a variant type could be so very
> useful. So unless I've misunderstood, this doesn't work (but it would be
> cool if it did).
>
> struct Variant {
>    enum ValueType {Long, Float, Double}
>
>    ValueType vt;
>    union {
>      long lng;
>      float fl;
>      double dbl;
>    }
>
>    T getValue(T)() @property
>    if (T == long || T == float || T == double) { //allowable types
>      static if (T == long) { //only long case written for brevity
>        switch(vt) {
>          //entries would likely be mixed in and not written manually...
>          case Long: return lng;
>          case Float:
>            assert(lng >= float.min && lng <= float.max);
>            return cast(float) lng;
>          case Float:
>            assert(lng >= double.min && lng <= double.max);
>            return cast(double) lng;
>        }
>      }
>
>      assert(0, "Fell through, should never get here");
>    }
> }
>
>
>   So then in theory
>
>   Variant v;
>   int i = v.getValue; //calls getValue!int()

You can use "alias this", but that only works for one type.

http://dlang.org/class.html#AliasThis

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list