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

后端 未结 3 1468
伪装坚强ぢ
伪装坚强ぢ 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 
    struct C {
      typedef typename std::conditional::type type;
    };
    

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

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

    template 
    using C = typename std::conditional::type;
    

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

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

    template 
    struct conditional {
      typedef A type;
    };
    
    template 
    struct conditional {
      typedef B type;
    };
    

提交回复
热议问题