All Recipes
Home/Concepts/Using Standard Library Concepts
🎯beginner

Using Standard Library Concepts

Leverage built-in concepts from <concepts> header

Example Code

cpp
#include <concepts>
#include <iostream>
#include <string>
// Use standard concepts for clean constraints
template<std::integral T>
T double_value(T value) {
return value * 2;
}
template<std::floating_point T>
T half_value(T value) {
return value / 2.0;
}
// Combine concepts with &&
template<typename T>
requires std::movable<T> && std::default_initializable<T>
T create_and_move() {
T obj{};
return std::move(obj);
}
int main() {
std::cout << double_value(21) << std::endl; // 42
std::cout << half_value(10.0) << std::endl; // 5.0
auto str = create_and_move<std::string>();
return 0;
}

Explanation

The <concepts> header provides many useful concepts like std::integral, std::floating_point, std::movable, std::copyable, and more. These can be combined using logical operators.

Key Points

  • 1std::integral - checks for integer types
  • 2std::floating_point - checks for float/double
  • 3std::movable, std::copyable - check move/copy semantics
  • 4Combine concepts with &&, ||, and !