C++ templates: Select different type based on value of template parameter

前端 未结 2 1925
清酒与你
清酒与你 2021-02-07 09:41

How do I accomplish the following in C++, and what is doing such things called?

template 
class NuclearPowerplantControllerFactoryProviderFactory {         


        
相关标签:
2条回答
  • 2021-02-07 10:24

    @Kerrek has answered the question sufficiently, but that can be more generic as follows:

    template<bool b, typename T, typename U>
    struct select
    {
        typedef T type;
    };
    template<typename T, typename U>
    struct select<false, T, U>
    {
        typedef U type;
    };
    

    And use as:

    template <bool S>
    class NuclearPowerplantControllerFactoryProviderFactory 
    {
      typedef typename select<S, int, unsigned int>::type data_t;
      //use data_t as data type
    };
    

    If S is true, the first type argument in select will be selected, or else second type argument will be selected. It is generic because you specify both types in select<>, and based on the value of the boolean, select<b,T,U>::type returns either first type, or second type.

    0 讨论(0)
  • 2021-02-07 10:42

    By specialization:

    template <bool> class Foo;
    
    template <> class Foo<true>
    {
      typedef int data_t;
    };
    
    template <> class Foo<false>
    {
      typedef unsigned int data_t;
    };
    

    You can choose to make one of the two cases the primary template and the other one the specialization, but I prefer this more symmetric version, given that bool can only have two values.


    If this is the first time you see this, you might also like to think about partial specialization:

    template <typename T> struct remove_pointer     { typedef T type; };
    template <typename U> struct remove_pointer<U*> { typedef U type; };
    


    As @Nawaz says, the easiest way is probably to #include <type_traits> and say:

    typedef typename std::conditional<S, int, unsigned int>::type data_t;
    
    0 讨论(0)
提交回复
热议问题