What is Concepts in C++: Simple Explanation and Example
concepts are a way to specify rules for template arguments, making templates easier to use and understand. They act like filters that check if a type meets certain requirements before compiling the code.How It Works
Think of concepts as a checklist for types used in templates. When you write a template, you want to make sure the types passed in have certain features, like supporting addition or comparison. Concepts let you write these rules clearly and check them automatically.
This is like hiring someone for a job: you list the skills needed, and only candidates who meet those skills are accepted. Similarly, concepts let the compiler accept only types that fit the rules, preventing confusing errors later.
Example
This example shows a concept that requires a type to support addition. The template function uses this concept to only accept types that can be added.
#include <iostream> #include <concepts> // Define a concept that requires the + operator template<typename T> concept Addable = requires(T a, T b) { { a + b } -> std::convertible_to<T>; }; // Function that uses the Addable concept template<Addable T> T add(T a, T b) { return a + b; } int main() { std::cout << add(5, 3) << "\n"; // Works with int std::cout << add(2.5, 4.1) << "\n"; // Works with double // std::cout << add("hi", " there"); // Error: const char* not Addable return 0; }
When to Use
Use concepts when writing templates to make your code safer and easier to understand. They help catch mistakes early by ensuring only suitable types are used. This is especially useful in large projects or libraries where templates are common.
For example, if you write a function that works only with numbers, concepts can prevent someone from accidentally passing a string, avoiding confusing errors during compilation.
Key Points
- Concepts define rules for template parameters.
- They improve code readability and error messages.
- Concepts act like filters to accept only valid types.
- Introduced in C++20 to modernize template programming.