On Wednesday, 17 July 2013 at 11:28:18 UTC, Andrej Mitrovic wrote:
I often need to re-initialize a variable back to its user-defined initializer. For variables that have no user-defined initializer, you
can simply use .init. For fields of structs or classes you can
actually use A.init.field, where A is the aggregate type. For example:

-----
struct S
{
    int value = 5;
}

void main()
{
    S s;
    s.value += 1;
    s.value = S.init.value;
    assert(s.value == 5);  // ok
}
-----

But there's no equivalent for variables which do not belong to any aggregate:

-----
void main()
{
    int value = 5;
    value += 1;
    // value = ??
    assert(value == 5);
}
-----

I think this is not a fair comparison. Your S s could be S s = S(2) and you cannot retrieve S(2) just like in case with int value = 5. I see no difference between basic type variables and user-defined variables here.

Also, this reminds me replacing typedef by alias with loosing one nice feature - you could do typedef MyInt int = 5; but not with alias.

One workaround is to factor out the initializer to a manifest
constant, for example:

Other approach is to use UDA, it may be better then enum, but one still need extra typing. Having new trait seems to be a good idea but it needs to be figured out how it behaves in different contexts.

Reply via email to