Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to constrain a template to a specific type

I am trying out template programming in C++ where I programmed a template for matrix.

template <
  typename T,
  unsigned int R, unsigned int C>
requires StringOrArithmeticType<T>
class matrix {
...
};

From the type traits I could constrain the T to floating point and integral types. How can I do it with for example a specific type like string?

template <typename T>
concept StringOrArithmeticType =
  is_integral_v<T> || is_floating_point_v<T> || is_string<T>::value;

So I implemented my own is_string. In type traits I could not find something helpful? Here I need some help, how should I solve this problem? Also, I would like to set the constrain that R and C must be greater than 1.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To check if the type is a string, use std::is_same_v<T, std::string>.

To constrain R and C, just add the appropriate conditions to the requires clause:

template<typename T, unsigned R, unsigned C>
requires (StringOrArithmeticType<T> && (R > 1) && (C > 1))
class matrix { ... };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading