Classes in D and C++
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Mon Mar 5 00:03:38 PST 2007
Bill Baxter wrote:
> Lionello Lunesu wrote:
>>
>> Instead of a constructor, create a "static opCall". opCall is the
>> overload for "(..)" so you can instantiate your type similar to C++:
>>
>> struct SomeType {
>> int member = 0;// default initializer here
>> static SomeType opCall( int whatever ) {
>> SomeType st;
>> st.member = whatever;//custom initialize
>> return st;
>> }
>> //...
>> }
>>
>> SomeType st = 2;//construction
>>
>> No need for constructors ;)
>
> I don't think that quite works as you wrote.
> I think it needs to be
> SomeType st = SomeType(2);
> or
> auto st = SomeType(2);
>
> if you want to avoid repeating your repeat-avoiding self repeatedly.
Actually, with a slight modification that compiles just fine:
---
struct SomeType {
int member = 0;// default initializer here
static SomeType opCall( int whatever ) {
SomeType st;
st.member = whatever;//custom initialize
return st;
}
//...
}
void main() {
SomeType st = 2;//construction
}
---
Static opCall isn't compile-time executable since it uses a struct :(,
so the declaration must be in a function. (This is actually a pretty
good argument to allow compile-time execution to work with structs, I think)
This has been allowed for a while now, see
http://www.digitalmars.com/d/changelog2.html#new0177 :
---
# Casting a value v to a struct S is now rewritten as S(v).
# Initializing a struct S from a value v is now rewritten as S(v).
---
More information about the Digitalmars-d
mailing list