Templated Struct Constructor

Andrew Wiley wiley.andrew.j at gmail.com
Fri Dec 9 23:42:30 PST 2011


On Sat, Dec 10, 2011 at 1:23 AM, Andrew Wiley <wiley.andrew.j at gmail.com> wrote:
> Is there a syntax that allows me to specify arguments to a templated
> constructor for a struct? The intuitive way looks like this, but it
> doesn't work.
>
> ---
> struct Test {
>        this(T, bool b)(T info) if((b && something ) || (!b && somethingElse)) {
>
>        }
> }
>
> void main() {
>        Test test = Test!(int, true)(5); // Error: template instance
> Test!(int,true) Test is not a template declaration, it is a struct
> }
> ---

Looks like I can work around it by doing this:
---
template makeTest(T, bool b) {
    static if((b && something) || (!b && somethingElse)) {
        alias Test makeTest;
    }
    else static assert(0, "some error message");
}
struct Test {
    private:
    this(T)(T info) {
    }
}
void main() {
    Test test = Test!(int, true)(5); // Error: template instance
    Test!(int,true) Test is not a template declaration, it is a struct
}
---

But this solution isn't very satisfying because Test is no longer
directly protected by the static checks I want.


More information about the Digitalmars-d mailing list