Static CT Factory

Engine Machine via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 18 18:10:42 PDT 2016


I have a template that is suppose to create a type based on a 
template parameter

static if (T == "int")
{
    auto x = New!int();
}
else static if (T == "double")
{
    auto x = New!double();
}

x = 1.234;


This is just an example, I use custom types.

The static if's prevent x's scope from being after them, even 
though it should work perfectly fine. I can't declare x before 
because I don't know the type.

The point is that I don't want to have to put x = 1.234; in each 
static if block when I should be able to do it perfectly fine 
afterwards.

My types that I'm creating all have a name field and I want to 
set it once after the object is created.

Luckily, all of them inherit from the same type and I can declare 
that before the static if block, but in general, that won't work.

I feel that in this case I feel that the scope of the static if 
should allow things to escape since, well, they are static if's. 
It would be similar to #ifdef.

I realize that D doesn't work this way, I'm asking for a nicer 
solution than having to duplicate the same code(x = 1.234 in this 
example) or having use a base class.



More information about the Digitalmars-d-learn mailing list