Named constructors
bauss
jj_1337 at live.dk
Wed Jan 9 10:02:12 UTC 2019
On Wednesday, 9 January 2019 at 08:53:40 UTC, Alex wrote:
> On Wednesday, 9 January 2019 at 07:47:02 UTC, Dru wrote:
>> Another way to distinguish between constructors is needed.
>> Because it is possible to have two different constructors that
>> take the same arguments.
>> Adding dummy arguments that are unused hurts code clarity.
>
> Couldn't this problem be solved by a factory method? I mean,
> either this, or something like this:
> http://www.cs.technion.ac.il/users/yechiel/c++-faq/named-ctor-idiom.html
>
> ´´´
> import std.stdio;
> import std.math;
>
> void main()
> {
> auto pr = Point.rectangular(2,3);
>
> assert(approxEqual(pr.x_, 2));
> assert(approxEqual(pr.y_, 3));
>
> auto pp = Point.polar(1,PI);
>
> assert(approxEqual(pp.x_, -1));
> assert(approxEqual(pp.y_, 0));
> }
>
>
> struct Point {
> public:
> static Point rectangular(real x, real y) // Rectangular
> coord's
> {
> return Point(x,y);
> }
> static Point polar(real radius, real angle) // Polar
> coordinates
> {
> return Point(radius * cos(angle), radius * sin(angle));
> }
>
> private:
> this(real x, real y)
> {
> x_ = x;
> y_ = y;
> }
> real x_, y_;
> }
> ´´´
I like this approach to it and you're entirely correct.
It would be nice with support for this in the language without
having to create factory methods.
Basically something like the following could be lowered to your
code.
´´´
import std.stdio;
import std.math;
void main()
{
auto pr = Point.rectangular(2,3);
assert(approxEqual(pr.x_, 2));
assert(approxEqual(pr.y_, 3));
auto pp = Point.polar(1,PI);
assert(approxEqual(pp.x_, -1));
assert(approxEqual(pp.y_, 0));
}
struct Point {
public:
this(real x, real y)
{
this.x = x;
this.y = y;
}
this rectangular(real x, real y)
{
this(x,y);
}
this polar(real radius, real angle)
{
this(radius * cos(angle), radius * sin(angle));
}
real x, y;
}
´´´
More information about the Digitalmars-d
mailing list