+ 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
2 RĂ©ponses
+ 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.
0
Function Templates
https://www.sololearn.com/learning/1051/1914/3788/1