discrimination of constructors with same number of parameters
sybrandy
sybrandy at gmail.com
Thu Dec 30 07:03:20 PST 2010
On 12/30/2010 08:46 AM, Lutger Blijdestijn wrote:
> sybrandy wrote:
>
>> Why not have something like this:
>>
>> this (int[] data, string text, bool isMessage = false) {...}
>>
>> Then, if you just pass in two parameters you treat it as a filename and
>> if you pass in a "true" for the third parameter, it's a message. It's
>> not quite what you're looking for, but it's simple and pretty clean.
>>
>> Casey
>
> If you opt for this solution, an enum is slightly more verbose but much
> clearer:
>
> enum IsMessage
> {
> Yes,
> No
> }
>
> this (int[] data, string text, IsMessage isMessage = IsMessage.No) {...}
>
>
> auto s = new S(data, text, IsMessage.Yes);
>
> vs
>
> auto s = new S(data, text, true);
I will agree that is clearer. I just had to do stuff like this for
different reasons and it worked very nicely.
>
>
> I would still prefer a factory method or a struct wrapper though.
True, I just don't know how without it being complex. I think this may
be the case where improvements to the type system would be useful. For
me, this situation doesn't come up very often, so I'm not all that
concerned, but I do see where this can be useful. I'm just not a fan of
having to write a lot of code to do something that the language can turn
into something simple.
However, another possible solution that just occurred to me is something
like this (please forgive any typos, I haven't done inheritance in D yet):
enum TextType { Filename, Message }
class Text
{
string text;
TextType type;
bool isMessage() { return TextType.Message == this.type; }
}
class Filename : Text
{
this(int[] data, string txt)
{
this.type = TextType.Filename;
this.text = txt;
// Do something with data...
}
}
class Message : Text
{
this(int[] data, string txt)
{
this.type = TextType.Message;
this.text = txt;
// Do something with data...
}
}
Then, you can do something like this:
Text foo = new Filename(data, filename);
Text bar = new Message(data, message);
Not sure if it's any better than using an enum, but it still has the
clarity that you're looking for.
Casey
More information about the Digitalmars-d-learn
mailing list