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

前端 未结 2 1928
清酒与你
清酒与你 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
    struct select
    {
        typedef T type;
    };
    template
    struct select
    {
        typedef U type;
    };
    

    And use as:

    template 
    class NuclearPowerplantControllerFactoryProviderFactory 
    {
      typedef typename select::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::type returns either first type, or second type.

提交回复
热议问题