CppCoreGuidelines
CppCoreGuidelines copied to clipboard
Example for T.122
T.122: Use templates (usually template aliases) to compute types at compile time
Example
template <size_t bits>
using int_least_bits_t = std::conditional_t<bits <= 32, int32_t, int64_t>;
int_least_bits_t<minimum_bits> x{ /* ... */ };
Wouldn't the example be better with int_least32_t and int_least64_t which are guaranteed to exist on all platforms?
Wouldn't the example be better with
int_least32_tandint_least64_twhich are guaranteed to exist on all platforms?
Yes, that is a good point:
template <size_t bits>
using int_least_bits_t = std::conditional_t<bits <= 32, int_least32_t, int_least64_t>;
int_least_bits_t<minimum_bits> x{ /* ... */ };
would be neat to also show "Bad" example, except what is the implied alternative? Even old C++ std::char_traits and Loki::TypeTraits::UnConst were templates..
There isn't much of an alternative. You need templates to compute types. The only non-template solution that comes to mind is union.