Redirect to different overloads at compile time?

Kenji Hara via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 29 21:50:03 PDT 2014


On Monday, 30 June 2014 at 02:24:10 UTC, David Bregman wrote:
> Suppose I have a C library which implements a function for 
> several types. C doesn't have overloading, so their names will 
> be distinct.
>
> extern(C):
> double foo_double(double);
> float foo_float(float);
>
> Now I want to build a D wrapper, and merge them into a single 
> function with overloading:
>
> T foo(T)
>
> I could write out the two overloads manually:
> double foo(double d) { return foo_double(d); }
> float foo(float f) { return foo_float(f); }
>
> but this isn't compile time, it will generate a stub function 
> for each overload, meaning the wrapper will have performance 
> overhead unless inlining can be guaranteed somehow.
>
> Is it possible to do something like
> alias foo = foo_double;
> alias foo = foo_float;

In D, you can merge arbitrary overloads by using alias 
declaration.

import std.stdio;
extern(C)
{
     double foo_double(double a) { writeln(typeof(a).stringof); 
return a; }
     float  foo_float (float  a) { writeln(typeof(a).stringof); 
return a; }
}

alias foo = foo_double;
alias foo = foo_float;

void main()
{
     double d;
     float f;
     foo(d);  // prints double
     foo(f);  // prints float
}

Kenji Hara


More information about the Digitalmars-d-learn mailing list