CppCoreGuidelines icon indicating copy to clipboard operation
CppCoreGuidelines copied to clipboard

Example for T.122

Open eisenwave opened this issue 2 years ago • 4 comments

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{ /* ... */ };

eisenwave avatar Jun 24 '23 12:06 eisenwave

Wouldn't the example be better with int_least32_t and int_least64_t which are guaranteed to exist on all platforms?

jwakely avatar Jun 24 '23 16:06 jwakely

Wouldn't the example be better with int_least32_t and int_least64_t which 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{ /* ... */ };

eisenwave avatar Jun 24 '23 16:06 eisenwave

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..

cubbimew avatar Jun 26 '23 21:06 cubbimew

There isn't much of an alternative. You need templates to compute types. The only non-template solution that comes to mind is union.

eisenwave avatar Jun 29 '23 08:06 eisenwave