I've a basic template class, but I'd like to restrain the type of the specialisation to a set of classes or types. e.g.:
template <typename T>
class MyClass
{
.../...
private:
T* _p;
};
MyClass<std::string> a; // OK
MYCLass<short> b; // OK
MyClass<double> c; // not OK
Those are just examples, the allowed types may vary.
Is that even possible? If it is, how to do so?
Thanks.
There are various tricks allowing to check for some things, depending on what your criteria is for the instantiation be allowed or not. In practice you should use an higher lever library for those like Boost's Concept Check.
Yust a quick idea, I'm sure there are better approaches:
It might be better, however, to put a fat comment over your code to keep users from instantiating with the wrong types :-)
Take a look at the Boost Concept Check Library: http://www.boost.org/doc/libs/1_42_0/libs/concept_check/concept_check.htm
Another version is to leave it undefined for the forbidden types
Generally it is unnecessary to restrict which types templates can be instantiated with. Either the template is compilable with the given type (and works OK) or it isn't (and produces a compiler error without any effort on the programmer's part).
If you need to put in restrictions, generally the types have something in common that may be described by some type traits that are already available (standard library,
boost::type_traits
), or you can create a new type trait for them.For example, here's a template class that only allows integer types, using
std::numeric_limits
to check it (if you write your own numeric type, you may specialize that so that it would also work with your new integer type).static_assert
is C++0x only, if not available useBOOST_STATIC_ASSERT
or some other trick.If you only plan to support a handful of arbitrary types with nothing in common (as is apparent from your hypothetical example), one way is to employ typelists. Again boost might make the task a lot easier, but here's how you might roll your own (this only goes half-way, additional work would be required to make declaring the typelist prettier).
Im not sure about this, but you could add another template specialization for double template
which would work for your example, but not for the general case.
In general, I would add a compile assert to check for unwanted types.
Hope it helps.