Yes, you can combine type traits with decltype
to inspect the type of a class member within a concept. Here's an example:
#include <concepts>
#include <type_traits>
template <typename T>
concept IntegralSized =
std::is_integral_v<
std::remove_cvref_t<decltype(T::Size)>>;
struct Asteroid {
long Size;
};
// Passes
static_assert(IntegralSized<Asteroid>);
In this example, the IntegralSized
concept checks if the Size
member of a class is an integral type.
We use decltype(T::Size)
to get the type of the Size
member. Since decltype
preserves cv-qualifiers and references, we use std::remove_cvref_t
to remove any const, volatile, and reference qualifiers from the type.
Finally, we use the std::is_integral_v
type trait to check if the resulting type is an integral type. The _v
suffix is a C++17 feature that provides a convenient way to get the value
member of a type trait as a bool
.
The static_assert
at the end confirms that the Asteroid
class, which has a long Size
member, satisfies the IntegralSized
 concept.
You can use various other type traits like std::is_floating_point
, std::is_base_of
, std::is_polymorphic
, etc., to create concepts that constrain class members based on their types and properties.
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.