this() in struct
Ali Çehreli
acehreli at yahoo.com
Tue Oct 9 10:56:18 PDT 2012
On 10/09/2012 10:08 AM, Zhenya wrote:
> On Tuesday, 9 October 2012 at 17:21:47 UTC, Zhenya wrote:
>> Hi!
>> I'm sorry,maybe this topic already was discussed,but could anybody
>> explain me
>> why default constructor was disallowed in structs?
>
> And if I have to do some initialization of data members,what is the way
> to do it?
I am not sure about the rationale myself. This issue is being discussed
at the main D forum:
http://forum.dlang.org/thread/fgldbozuneoldxjrwxje@forum.dlang.org
Here is what I know: If the initial values are the same for all objects,
then use initial values:
struct S
{
int i = 42;
double d = 1.5;
}
If you do not want to keep the initial values or they are not available
at compile time, then you can use a 'static opCall':
struct S
{
int i;
double d;
static S opCall()
{
S result;
result.i = 43;
result.d = 2.5;
return result;
}
}
void main()
{
auto s = S();
}
But then that opCall gets in the way and you can't write the following
any more:
auto s = S(44, 5.5);
/*
Error: function deneme.S.opCall () is not callable using
argument types (int,double)
Error: expected 0 arguments, not 2 for non-variadic function
type S()
*/
It still resolves to the static opCall even though the parameters don't
match.
Ali
More information about the Digitalmars-d-learn
mailing list