Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ concept that checks a value for requirements

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?

like image 614
Symlink Avatar asked Oct 18 '25 15:10

Symlink


1 Answers

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

like image 136
康桓瑋 Avatar answered Oct 21 '25 04:10

康桓瑋