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.
Another version is to leave it undefined for the forbidden types
template<typename T>
struct Allowed; // undefined for bad types!
template<> struct Allowed<std::string> { };
template<> struct Allowed<short> { };
template<typename T>
struct MyClass : private Allowed<T> {
// ...
};
MyClass<double> m; // nono
Yust a quick idea, I'm sure there are better approaches:
template <typename T> struct protector {
static const int result = 1;
};
template <> struct protector<double> {
static const int result = -1;
};
template <typename T>
class MyClass
{
private:
char isfine[protector<T>::result];
};
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With