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

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

    This is a fairly simple metafunction:

    template <int N>
    struct C {
      typedef typename std::conditional<N == 1,A,B>::type type;
    };
    

    You would use this as C<1>::type foo;.

    If your compiler supports C++11 template aliases, you can simplify to:

    template <int N>
    using C = typename std::conditional<N == 1,A,B>::type;
    

    and have your preferred C<1> foo; syntax.

    In pure C++03, implement std::conditional as:

    template <bool, typename A, typename>
    struct conditional {
      typedef A type;
    };
    
    template <typename A, typename B>
    struct conditional<false, A, B> {
      typedef B type;
    };
    
    0 讨论(0)
  • 2021-02-09 23:35

    Using the LSP and plain C++98:

    template <int N> 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.

    0 讨论(0)
  • 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 <int N>
    struct choices;
    
    template <>
    struct choices<1> { typedef A type; };
    
    template <>
    struct choices<2> { typedef B type; };
    
    template <int N>
    using C = typename choices<N>::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 <int N>
    struct C
    {
        typedef typename choices<N>::type type;
    };
    
    // ...
    C<1>::type anInstanceOfA;
    C<2>::type anInstanceOfB
    
    0 讨论(0)
提交回复
热议问题