0
0
CppConceptBeginner · 3 min read

Concepts in C++20: What They Are and How to Use Them

In C++20, concepts are a way to specify rules or requirements for template parameters, making templates easier to use and understand. They act like named checks that ensure types meet certain conditions before compiling.
⚙️

How It Works

Concepts in C++20 work like a checklist for template parameters. Imagine you want to bake a cake, but you need specific ingredients like eggs and flour. Concepts let you define what ingredients (properties) are needed before you start baking (compiling).

When you write a template, you can attach a concept to its parameters. The compiler then checks if the types you provide meet those rules. If they don't, it gives clear errors, so you know exactly what is missing.

This makes templates safer and easier to understand because you don't get confusing errors deep inside the code. Instead, you get a simple message about what requirement failed.

💻

Example

This example shows a concept that checks if a type supports addition, then uses it in a template function.

cpp
#include <iostream>
#include <concepts>

// Define a concept named Addable
template<typename T>
concept Addable = requires(T a, T b) {
    { a + b } -> std::convertible_to<T>;
};

// Use the concept in a template function
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;
}
Output
8 6.6
🎯

When to Use

Use concepts when you write templates that should only work with certain types. They help catch mistakes early and make your code easier to read.

For example, if you write a function that adds two values, you want to make sure the types support addition. Concepts let you express this clearly.

They are especially useful in large projects or libraries where many people use your templates, so errors are easier to understand and fix.

Key Points

  • Concepts define rules for template parameters.
  • They improve code readability and error messages.
  • Concepts are checked at compile time.
  • They help write safer and clearer generic code.

Key Takeaways

Concepts let you specify clear requirements for template types in C++20.
They improve error messages by checking rules before compiling template code.
Use concepts to make templates safer and easier to understand.
Concepts help catch type-related mistakes early in large or shared codebases.