Factory pattern in D

Namespace via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 1 03:07:57 PDT 2015


On Friday, 1 May 2015 at 10:04:46 UTC, Namespace wrote:
> How about this:
>
> ----
> struct A {
>   int x = 42;
> }
>
> struct B {
>   int x = 7;
> }
>
> T factory(T)() {
>   return T();
> }
>
> void main()
> {
>   auto a = factory!(A);
> }
> ----

Of course, you can restrict the type to A or B, or both:
----
T factory(T)() if (is(T == A) || is(T == B)) {
   return T();
}
----


More information about the Digitalmars-d-learn mailing list