When designing template classes that take only numeric types, such as int/double, is there a specific way to allow only these two types (for instance), or when using a template is it up to the programmer to be aware of what types are allowed?
I believe that the answer is yes (offhand: you specialise the class template for those types, but leave it with say, a static assertion otherwise), but generally you would not want to do this since if the type behaves like an int or a double for your purposes, you would want to allow it.
Sorry, you have completely lost me! :) I am only just starting to read up on templates.
Originally Posted by laserlight
So, for example, I have an exercise in my book where I create a template Number<T> where T can be any numeric type. Is there a method to restrict types to only those that are numeric? If so, what do I need to read up on?
Yes. For example:
But keep in mind that you shouldn't restrict types like this unless you absolutely need it. For example, if your code doesn't--or cannot--handle certain types, you can ban them or allow only specific ones.
template<typename T> class MyClass
static_assert(false, "Type must be int.");
template<> class MyClass<int>
// Your class here
Okay thanks. That's pretty much answered it.