Any better way to do this virtual constructor?

N

Nan Li

Hello,
I have the following code now.

enum T1
{ A, B, C };

enum T2
{ D, E, F };


class Base
{
};

template < T1, T2 >
class Derived : public Base
{
} ;

Base * build( T1 t1, T2 t2 )
{
if ( t1 == A and t2 == D )
{
return new Derived<A,D>();
}
if ( t1 == A and t2 == E )
{
return new Derived<A,E>();
}
if ( t1 == A and t2 == F )
{
return new Derived<A,F>();
}
// ..... all the combinations here
}

I really hate to list all the T1-T2 combinations in the 'build'
functions. Is there any better way to code this? t1 and t2 are known
only at run time.

Thanks a lot !
 
D

Daniel Pitts

Nan said:
Hello,
I have the following code now.

enum T1
{ A, B, C };

enum T2
{ D, E, F };


class Base
{
};

template < T1, T2 >
class Derived : public Base
{
} ;

Base * build( T1 t1, T2 t2 )
{
if ( t1 == A and t2 == D )
{
return new Derived<A,D>();
}
if ( t1 == A and t2 == E )
{
return new Derived<A,E>();
}
if ( t1 == A and t2 == F )
{
return new Derived<A,F>();
}
// ..... all the combinations here
}

I really hate to list all the T1-T2 combinations in the 'build'
functions. Is there any better way to code this? t1 and t2 are known
only at run time.

Thanks a lot !

Yes, don't make them template parameters, but member values instead. Is
there a reason that you need different types for this?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top