Using Concepts with Classes

Requiring Method Signature

Can I constrain a class to have a method with a specific signature using concepts?

Abstract art representing computer hardware

Yes, you can use a functional-style requires expression within your concept to specify that a class has a method with a certain signature. Here's an example:

#include <concepts>

template <typename T>
concept Renderable =
  requires(T obj, int x, int y) {
    { obj.Render(x, y) } -> std::same_as<void>;
};

struct Sprite {
  void Render(int x, int y);
};

static_assert(Renderable<Sprite>);  // Passes

The Renderable concept requires that for a type T, it must have a member function Render that is callable with two int arguments x and y, and returns void.

The requires expression provides a way to describe the expected function signature. The obj parameter represents an instance of type T, and x and y serve as the arguments to the Render function.

The return type requirement { obj.Render(x, y) } -> std::same_as<void> specifies that invoking Render with x and y should return something of type void.

If the Sprite class meets these requirements (which it does in this case), the static_assert will pass. If Sprite::Render had a different signature, a compile error would occur.

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:

  • 124 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