Function overloading

Regan Heath regan at netmail.co.nz
Tue Jul 31 02:43:47 PDT 2007


Frits van Bommel wrote:
> Regan Heath wrote:
>> import std.stdio;
>>
>> void test(T)(T p)
>> {
>>     writefln("misc called");
>> }
>>
>> void test(T : int)(T p)
>> {
>>     writefln("int called");
>> }
>>
>> void main()
>> {
>>     int i;
>>     long l;
>>     float f;
>>     test!(int)(i);
>>     test!(long)(l);
>>     test!(float)(f);
>> }
>>
>> Output:
>> int called
>> misc called
>> misc called
>>
>>
>> However, without the !(int) etc it fails to compile with: "template 
>> tplspec.test(T : int) specialization not allowed for deduced parameter T"
> 
> Workaround:
> ---
> import std.stdio;
> 
> void testImpl(T)(T p)
> {
>     writefln("misc called");
> }
> 
> void testImpl(T : int)(T p)
> {
>     writefln("int called");
> }
> 
> void test(T)(T p) { return testImpl!(T)(p); }
> 
> void main()
> {
>     int i;
>     long l;
>     float f;
>     test(i);
>     test(l);
>     test(f);
> }
> ---
> (test uses the deduced parameter to explicitly instantiate testImpl)

Nice!

Regan


More information about the Digitalmars-d-learn mailing list