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
, double
, float
, etc.) as template?
You can use the std::is_arithmetic
type trait. If you want to only enable instantiation of a class with such a type, use it in conjunction with std::enable_if
:
#include <type_traits>
template<
typename T, //real type
typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type
> struct S{};
int main() {
S<int> s; //compiles
S<char*> s; //doesn't compile
}
For a version of enable_if
that's easier to use, and a free addition of disable_if
, I highly recommend reading this wonderful article on the matter.
p.s. 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.