Constrained Template Parameters
Learn how constrained template parameters can be used to define constraints for the class templates.
We'll cover the following...
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:
Press + to interact
#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
...