auto limitation?

Ali Çehreli acehreli at yahoo.com
Tue Sep 11 11:48:25 PDT 2012


On 09/11/2012 11:40 AM, Namespace wrote:
 >> Here is a reduced code:
 >>
 >> import std.stdio;
 >>
 >> enum Type { Int, Float }
 >>
 >> auto foo(Type t)
 >> {
 >> final switch (t) {
 >> case Type.Int:
 >> return 42;
 >> case Type.Float:
 >> return 1.5;
 >> }
 >> }
 >>
 >> void main()
 >> {
 >> writeln(foo(Type.Int));
 >> writeln(foo(Type.Float));
 >> }
 >>
 >> The return type of foo() is double. (It's float in your code but it
 >> doesn't matter.)
 >>
 >> I think this is a bug. I guess that 'return 42' is still placing an
 >> int onto the program stack instead of a float. A workarounds are
 >> returning to!float(this._num.ivalue).
 >>
 >> But I think this is a compiler bug.
 >>
 >> Ali
 >
 > I should begin to count the bugs I find with stuff like this. :)

Please create a bug about this one:

   http://d.puremagic.com/issues/

But wait until someone else confirms that it really is a bug. :)

 > So no correct workaround, hm?

You have to cast the types to the largest one. The following does not 
work because foo() is not defined yet:

import std.traits;
// ...
auto foo(Type t)
{
     final switch (t) {
     case Type.Int:
         return to!(ReturnType!(typeof(&foo)))(42);
     case Type.Float:
         return 1.5;
     }
}

   Error: forward reference to foo

Explicitly casting is a way:

         return to!double(42);

Or you can write or find a template that produces the largest type among 
the members of a union.

Ali



More information about the Digitalmars-d-learn mailing list