Using Concepts with Classes

Checking Member Type with Type Traits

Can I use type traits to check the type of a class member within a concept?

Abstract art representing computer hardware

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.

This Question is from the Lesson:

Using Concepts with Classes

Learn how to use concepts to express constraints on classes, ensuring they have particular members, methods, and operators.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Using Concepts with Classes

Learn how to use concepts to express constraints on classes, ensuring they have particular members, methods, and operators.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved