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

前端 未结 2 1959
清酒与你
清酒与你 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:42

    By specialization:

    template  class Foo;
    
    template <> class Foo
    {
      typedef int data_t;
    };
    
    template <> class Foo
    {
      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  struct remove_pointer     { typedef T type; };
    template  struct remove_pointer { typedef U type; };
    


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

    typedef typename std::conditional::type data_t;
    

提交回复
热议问题