'new' class method
Bill Baxter
wbaxter at gmail.com
Thu Oct 23 12:57:19 PDT 2008
On Thu, Oct 23, 2008 at 9:26 PM, dsimcha <dsimcha at yahoo.com> wrote:
> == Quote from Yigal Chripun (yigal100 at gmail.com)'s article
>> Bill Baxter wrote:
>> > On Thu, Oct 23, 2008 at 6:32 PM, bearophile
>> > <bearophileHUGS at lycos.com> wrote:
>> >> In Python to create new instances of a class you use the normal
>> >> function call syntax, this allows you to use them as factory
>> >> functions:
>> >>
>> >> class C: def __init__(self, id): self.id = id def __repr__(self):
>> >> return "<%s>" % self.id seq = map(C, [1, -5, 10, 3])
>> >>
>> >> That creates an array (list) of four objects.
>> >>
>> >> In D with a map() you can do something similar:
>> >>
>> >> import d.all; import std.string: format;
>> >>
>> >> class C { int id; this(int id) { this.id = id; } string toString()
>> >> { return format("<%s>", this.id); } static C opCall(int id) {
>> >> return new C(id); } } void main() { auto seq = map((int id){return
>> >> new C(id);}, [1, -5, 10, 3]); putr(seq); }
>> >>
>> >> You can use the opCall method in a more direct way:
>> >>
>> >> auto seq2 = map(&(C.opCall), [1, -5, 10, 3]); putr(seq2);
>> >>
>> >> But probably even better is to replace the current new syntax with
>> >> a class method that creates the instances (I think the Ruby
>> >> language has such syntax):
>> >>
>> >> auto seq3 = map(C.new, [1, -5, 10, 3]); putr(seq3);
>> >
>> > That would be map(&(C.new), [1,-5,10,3]); wouldn't it?
>> >
>> >> With that normal code like:
>> >>
>> >> new Foo(10, 20)
>> >>
>> >> becomes:
>> >>
>> >> Foo.new(10, 20)
>> >>
>> >> Not a big change but allows a more functional style of coding.
>> >
>> > I like it. Can we get rid of delete's specialness too?
>> >
>> > Maybe just delete(anInstance); Make it like a normal function too.
>> > Enabling things like
>> >
>> > map(&delete, [obj1, obj2, obj3])
>> >
>> > --bb
>> Andrei already mentioned that he wants to get read of new/delete IIRC.
>> I like Ruby's way of making it regular methods. something like:
>> obj.new(..) and obj.delete()
>> but, how do you specify stack vs heap allocation?
>> something like:
>> auto a = new S(); //on heap
>> auto b = S(); //on stack
>> also, what about placement new?
>
> One thing I would definitely like to see is for struct and class syntax to be
> unified so that if you change a struct to a class or vice versa, this doesn't
> require changes all over your code. Then again, the reference vs. value semantic
> issue may bite you anyhow.
To me this makes a lot of sense:
auto a = SomeStruct(); // a is a struct on the stack
auto b = SomeClass(); // b is a class on the heap
It kills static opCall for classes, but who cares. I'm often tempted
to write static opCalls for classes like this anyway:
static SomeClass opCall() { return new SomeClass(); }
Just to get the uniformity of construction syntax.
--bb
More information about the Digitalmars-d
mailing list