May I use a constant number to choose a class at compile time, possibly using templates?

后端 未结 3 1467
伪装坚强ぢ
伪装坚强ぢ 2021-02-09 22:49

Let\'s say I have a constant value (possibly of some enum type). Let\'s say I have many classes A, B, D, etc.

Can I have something like this?

C<1>          


        
3条回答
  •  迷失自我
    2021-02-09 23:35

    Using the LSP and plain C++98:

    template  class C;
    template <> class C<1> : public A {};
    template <> class C<2> : public B {};
    template <> class C<3> : public D {};
    
    C<1> anInstanceOfA;
    

    Since public inheritance in C++ satisfies the IS-A rule, anInstanceOfA both IS-A C<1> object and IS_AN A object.

提交回复
热议问题