How do I disable implicit struct constructor calls (and is that a good idea)?

Max Marrone via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 15 17:39:25 PST 2014


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.


More information about the Digitalmars-d-learn mailing list