Magic type return

Andrea Fontana nospam at example.com
Thu Jul 19 00:28:33 PDT 2012


Or template inference based on return type like

T hello(T)()
{
    static if (is(T ==)) ....

}

string v = hello();

Il giorno mer, 18/07/2012 alle 17.38 +0100, Regan Heath ha scritto:

> On Tue, 17 Jul 2012 15:23:05 +0100, bearophile <bearophileHUGS at lycos.com>  
> wrote:
> 
> > Andrea Fontana:
> >
> >> class Known
> >> {
> >>          void* data; // external data by c api
> >>          int type;  // 0 for int, 1 for string, etc. ..
> >> }
> >>
> >> How can I implement a method like this?
> >>
> >> Known  known;  // <-- suppose known.type == 1;
> >> string s  = known.value(); // <-- automatic
> >
> > To do this Known.value() needs to return different types according to  
> > the run-time value of Known.type. This is not possible in a statically  
> > typed language... You need to find other solutions.
> 
> Unless we had overload based on return type, right?
> 
> e.g.
> 
> class Known
> {
>    string value()
>    {
>      if (type != 1)
>        throw..;
>      return cast(string)data;
>    }
> 
>    int value()
>    {
>      if (type != 0)
>        throw ..;
>      return cast(int)data;
>    }
> }
> 
> The compiler could produce the correct code/call for the line
> 
> string s = known.value();
> 
> then, but it's not a feature we're likely to see any time soon.
> 
> R
> 


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20120719/abb90a00/attachment-0001.html>


More information about the Digitalmars-d-learn mailing list