C++ template generics | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

C++ template generics

How do I only accept certain types? I don’t want char or string, just ints, floats, and doubles. But I don’t know if you can do this with c++ templates

11th Aug 2022, 2:17 AM
ITDW
2 Answers
+ 2
If you have a C++20 compiler that implements concepts, they are the way to go: https://en.cppreference.com/w/cpp/language/constraints Otherwise, you can use type traits to impose conditions on your template types. The STL has a variety of predefined concepts and traits: https://en.cppreference.com/w/cpp/concepts https://en.cppreference.com/w/cpp/meta#Type_traits The following is an example how to craft your own concept/trait for the scenario you described: https://code.sololearn.com/cwpEEai89TW9/?ref=app However, note that implicit type conversion does not work with this approach - foo() can only accept the type int but no other integral variation such as unsigned integers, shorts, and so on. If that behaviour is undesirable and you have a limited type set, you can consider function overloading as an alternative.
11th Aug 2022, 1:06 PM
Shadow
Shadow - avatar
11th Aug 2022, 3:06 AM
SoloProg
SoloProg - avatar