Home > Enterprise >  C concept that checks a value for requirements
C concept that checks a value for requirements

Time:02-20

Is there a way to use c 20s concepts to check that a value meets some requirements?

Lets say I am writing some sort of container that uses paging and i want to make the page size a template parameter.

template<typename Type, std::size_t PageSize>
class container;

I could use a static assert with a constexpr function to check if PageSize is a power of two inside the class body.

But is there a way to use the new concepts to restrain PageSize?

CodePudding user response:

C 20 introduced std::has_single_bit to check if x is an integral power of two, so you can use requires expression to constrain PageSize.

#include <bit>

template<typename Type, std::size_t PageSize>
  requires (std::has_single_bit(PageSize))
class container { };

Demo

CodePudding user response:

The easiest way would be to constrain the template parameters of the class.

constexpr bool is_power_of_two(std::size_t x) { /*... */ }

template<typename Type, std::size_t PageSize>
    requires ( is_power_of_two(PageSize) )
class container;
  • Related