discrimination of constructors with same number of parameters

spir denis.spir at gmail.com
Thu Dec 30 02:50:55 PST 2010


Hello,


When 2 constructors (*) accept the same number of parameters, the only remaining discrimination is type. Right? But some language types (or machine types) can have very diverse _human_ semantics, and thus be used for various purposes which should, but cannot, be considered different:
	this (int[] data, string filename) {...}
	this (int[] data, string message) {...}
Aliasing like in
	alias string Name;
does not help since for D Name is still string.

I know about typedef, but it is not even mentionned in TDPL, so I guess it is on the deprecation path. (Am I right?) So, what is the solution for this? (I added a 3rd fake bool parameter in one case)

Things get more complicated with unsigned integers: they can be used as ordinals (index, which one), as cardinals (count, how many), as any of the char types. These are completely different semantics for the "modeller" (the programmer), but for the language (thus for the machine) they are the same semantics.

Things get worse with template parameterisation, a case I lately met:
    Struct S (Element) {
	this (int[] data, string message) {...}
	this (int[] data, Element element) {...}
What happens when Element is string? Below an example:

struct S(Typ) {
    this(int) {writeln("int");}
    this(Typ) {writeln("Typ");}
}
unittest {
    auto s1 = S!string(1);
    auto s1 = S!int(1);
}
==>
rdmd -w -debug -unittest -L--export-dynamic --build-only -of"__trials__" "__trials__.d"

__trials__.d(42): Error: constructor __trials__.S!(int).S.this called with argument types:
	((int))
matches both:
	__trials__.S!(int).S.this(int _param_0)
and:
	__trials__.S!(int).S.this(int _param_0)

Compilation failed.

How do you cope with such cases?

Denis

(*) or any other func, in fact, but the issue shows up more frequently on constructors, because they have good reasons to accept various parameter sets.
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d-learn mailing list