Any better way to do this virtual constructor?

Discussion in 'C++' started by Nan Li, Jun 18, 2008.

  1. Nan Li

    Nan Li Guest

    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 !
     
    Nan Li, Jun 18, 2008
    #1
    1. Advertising

  2. Nan Li

    Daniel Pitts Guest

    Nan Li wrote:
    > 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?

    --
    Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
     
    Daniel Pitts, Jun 18, 2008
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Hitesh Joshi
    Replies:
    1
    Views:
    263
    Sybren Stuvel
    Jul 19, 2006
  2. neoedmund
    Replies:
    2
    Views:
    259
    Peter Otten
    Dec 27, 2006
  3. Generic Usenet Account
    Replies:
    10
    Views:
    2,246
  4. wolverine

    any better way to do this [getting gmt] ?

    wolverine, Sep 5, 2007, in forum: Javascript
    Replies:
    0
    Views:
    71
    wolverine
    Sep 5, 2007
  5. Replies:
    2
    Views:
    56
    Mark H Harris
    May 13, 2014
Loading...

Share This Page