November 16, 2014 How do I disable implicit struct constructor calls (and is that a good idea)? | ||||
|---|---|---|---|---|
| ||||
I was surprised to find that single-parameter struct constructors can be called implicitly:
struct Foo
{
string s;
this(string s) { this.s = s; }
}
void main()
{
Foo foo = "bar"; // Here.
assert(foo.s == "bar");
}
I don't believe this syntax makes sense for my struct and I'd like to disallow it. I want to permit only Foo foo = Foo("bar") and, if possible, Foo foo = {"bar"}.
Now, normally, I'd just leave the constructor out. However, I also want a (non-static) opCall, and so I need to define a constructor to retain struct literal initialization syntax.
Is there any way for me to keep my opCall, keep struct literal syntax, and still disallow Foo foo = "bar"? And is it even worth it? I don't like the fact that the constructor can be called implicitly like that, but maybe I'm just missing something.
| ||||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply