You can constrain the type of a class member variable within a concept using std::same_as
along with decltype
. Here's an example:
#include <concepts>
template <typename T>
concept IntegerSized = std::same_as<
int, std::remove_cvref_t<decltype(T::Size)>>;
struct Rock {
int Size;
};
// Passes
static_assert(IntegerSized<Rock>);
In this concept, std::same_as
checks if the member T::Size
has the same type as int
. We use std::remove_cvref_t
to remove any const, volatile, or reference qualifiers from the type before the comparison.
The static assertion static_assert(IntegerSized<Rock>)
will trigger a compile error if the Size
member of Rock
is not an int
.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to use concepts to express constraints on classes, ensuring they have particular members, methods, and operators.
Comprehensive course covering advanced concepts, and how to use them on large-scale projects.
View Course