Using Concepts with Classes

Constraining Member Variable Type

How can I require a class member variable to be of a specific type using concepts?

Abstract art representing computer hardware

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.

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