How do I write a class template that accepts only numeric types (int, double, float, etc.) as template?
How do I write a class template that accepts only numeric types ( int
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use the
std::is_arithmetictype trait. If you want to only enable instantiation of a class with such a type, use it in conjunction withstd::enable_if:For a version of
enable_ifthat’s easier to use, and a free addition ofdisable_if, I highly recommend reading this wonderful article on the matter.In C++, the technique described above has a name called "Substitution Failure Is Not An Error" (most use the acronym SFINAE). You can read more about this C++ technique on wikipedia or cppreference.com.
As of C++20, concepts make this much easier and don’t spoil the interface:
Do note that there are many user types meant to be used arithmetically as well, though, so a more general concept that covers the operations you’re looking for instead of the types you’re looking for would be preferable in a generic interface.