Concepts in C++20

Using Type Traits in Requires Clauses

Can I use type traits in a requires clause to constrain template parameters?

Abstract art representing computer hardware

Yes, you can use type traits in a requires clause to constrain template parameters based on specific properties or relationships between types. This allows you to leverage the existing type traits library in combination with concepts. Here's an example:

#include <type_traits>

class Player {};
class Goblin {};

template <typename T>
  requires std::is_base_of_v<Player, T>
void attack(T& attacker, Goblin& target) {
  // Attack implementation
}

int main() {
  Player player;
  Goblin goblin;

  // Valid, Player is a base of Player
  attack(player, goblin);
  
   // Invalid, Goblin is not a base of Player
  attack(goblin, goblin);
}
error: 'attack': no matching overloaded function found
could be 'void attack(T &,Goblin &)'
the associated constraints are not satisfied
the constraint was not satisfied

In this example, the attack function template is constrained using the std::is_base_of_v type trait in the requires clause. This ensures that the attacker parameter is of a type that derives from the Player class.

Attempting to call the function with a Goblin as the attacker will result in a compilation error.

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

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