Search⌘ K
AI Features

Constrained Template Parameters

Explore how constrained template parameters work in C++ Concepts to enforce type requirements directly in templates. Understand their advantages, limitations, and how they improve readability and error messages while developing safer generic code.

How constrained template parameters are applied

Constrained template parameters make it even easier to use concepts. In the template parameter list, instead of the typename keyword, we can simply write the name of the concept that we want to use.

Here is an example:

C++
#include <concepts>
#include <iostream>
template <typename T>
concept Number = std::integral<T> || std::floating_point<T>;
template <Number T>
class WrappedNumber {
public:
WrappedNumber(T num) : m_num(num) {}
private:
T m_num;
};
int main() {
WrappedNumber wn{42};
// WrappedNumber ws{"a string"}; // template constraint failure for 'template<class T> requires Number<T> class WrappedNumber'
}

In this example, we can see how we constrained T to satisfy the Number concept.

The clear ...