matching overloaded functions (std.string.toString)

Jarrett Billingsley kb3ctd2 at yahoo.com
Sat Feb 3 17:37:26 PST 2007


"Rick Mann" <rmann-d-lang at latencyzero.com> wrote in message 
news:eq2ssi$14jh$1 at digitaldaemon.com...

> So, I tried defining my own toString(OSStatus):
>
> char[]
> toString(OSStatus inVal)
> {
> return std.string.toString(cast (int) inVal);
> }
>
>
> But I get the same error.
>
> Can someone tell me why? Surely an exact match would be acceptable. 
> Thanks!

I'm assuming that you've declared this type and toString function in a 
module which you're importing, since defining it in the same file that it's 
used works.

So say youd have your file ostypes.d:

module ostypes;

import std.string;

typedef int OSStatus;

char[] toString(OSStatus s)
{
    return std.string.toString(cast(int)s);
}


And then you import it from main.d:

module main;

import std.string;
import ostypes;

void main()
{
    A a = 6;
    writefln(toString(a));
}

You get the error that you quoted.  This is because D does not do function 
overloading across modules.  The answer I got as to why this happens is that 
"it's the way C++ does it."  I never quite understood that rationale. 
(Interestingly one of my very first threads in this newsgroup was about a 
problem very similar to yours!)

So you have to "bring in" the toString symbols into a module that imports 
modules with conflicting symbols.  You do this with aliases:

module main;

import std.string;
import ostypes;

alias std.string.toString toString;
alias ostypes.toString toString;

void main()
{
    A a = 6;
    writefln(toString(a));
}

You have to have an alias for each module that overloads the function and 
for each function that's overloaded in more than one module.  If you leave 
out the first alias (that brings in std.string.toString), you'll be able to 
use toString for your OSStatus type but not for any other types.

This is really ugly. 




More information about the Digitalmars-d-learn mailing list