Using Type Traits in Requires Clauses

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

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.

Concepts in C++20

Learn how to use C++20 concepts to constrain template parameters, improve error messages, and enhance code readability.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Using Concepts with Class Templates
How can I use concepts to constrain the types allowed for a class template?
Combining Concepts with Logical Operators
Can I combine multiple concepts using logical operators in a requires clause?
Concepts and Abbreviated Function Templates
How can I use concepts with abbreviated function templates?
Using Trailing Requires Clauses
What are trailing requires clauses and when should I use them?
Benefits of Using Concepts
What are the main benefits of using concepts in C++20?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant