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

后端 未结 3 1536
伪装坚强ぢ
伪装坚强ぢ 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:41

    This isn't the only way to do this, but I hope acceptable for your purposes:

    struct A { };
    struct B { };
    
    template 
    struct choices;
    
    template <>
    struct choices<1> { typedef A type; };
    
    template <>
    struct choices<2> { typedef B type; };
    
    template 
    using C = typename choices::type;
    

    Update: To do the same without C++11 features, you should make C a class with a typedef member type equal to the corresponding type alias above:

    template 
    struct C
    {
        typedef typename choices::type type;
    };
    
    // ...
    C<1>::type anInstanceOfA;
    C<2>::type anInstanceOfB
    

提交回复
热议问题