How to prevent direct public creation of a struct?
Jonathan M Davis
jmdavisProg at gmx.com
Thu May 3 14:58:57 PDT 2012
On Thursday, May 03, 2012 17:37:47 Nick Sabalausky wrote:
> I want to do something like this:
>
> ------------------------------------------
> module moduleFoo;
>
> // Only allow certain values of "str"
> template foo(string str)
> {
> static assert(str == "a" || str == "b" || str == "c");
> immutable foo = Foo(str);
> }
>
> struct Foo
> {
> // Only "a", "b", and "c" should be allowed,
> // checked at compile-time via "template foo".
> // Also, not modifyable.
> private string _str;
> @property string str()
> {
> return _str;
> }
> }
> ------------------------------------------
>
> I want struct Foo itself to be public, but I want to *force* all code
> outside moduleFoo to *create* Foo via the "foo" template. Copying should be
> allowed though. Ie:
>
> ------------------------------------------
> auto a = foo!"a"; // ok
> a.str = "b"; // Error: str is a read-only property
> auto z = foo!"z"; // Error: fails static assert
> auto a2 = a; // Copy it: ok
>
> auto b = Foo("b"); // Error: I want to *force* the usage of "template foo"
>
> Foo x; // Kinda ambivalent about this: I'd prefer if it were disallowed, but
> I don't think that's possible. If it's indeed impossible, I know I can just
> declare Foo.str as (string str = "a";) so that's not a big problem.
> ------------------------------------------
>
> The *key* thing here that I'm not sure how to do is: How do I disallow
> this?:
>
> auto b = Foo("b"); // Error: I want to *force* the usage of "template foo"
Make all constructors private. Then the only way to construct the struct would
be through it's init value. If you use
@disable this();
you can also prevent the use of init, but that disables init completely, not
just outside of the module that the struct is in.
It looks like you're relying on the default-generated constructor for POD
structs, and that isn't going to cut it, since it's public. You'll have to
declare the appropriate constructor and make it private.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list