Mapping an integral template parameter value onto a primitive type

后端 未结 2 859
陌清茗
陌清茗 2021-01-15 22:07

I want to map a number to a type. For this example I\'ll make a function that maps a sizeof() result onto a signed primitive type.

I am wondering if there is a bette

2条回答
  •  广开言路
    2021-01-15 22:31

    I would not use C++17 if constexpr for this, instead I'd use template specialization, as it looks more declarative to me.

    Something along the following lines:

    template struct SizeToType {static_assert(S != S, "Wrong size"); };
    
    template<> struct SizeToType<1> { using type = uint8_t; };
    template<> struct SizeToType<2> { using type = uint16_t; };
    template<> struct SizeToType<4> { using type = uint32_t; };
    template<> struct SizeToType<8> { using type = uint64_t; };
    
    template
    using SizeToToTypeT = typename SizeToType::type;
    

    Adding more types would be just adding more specializations (one-liners) here.

提交回复
热议问题