Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force type of C++ template

Tags:

c++

templates

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.

like image 468
gregseth Avatar asked Mar 16 '10 14:03

gregseth


3 Answers

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
like image 124
Johannes Schaub - litb Avatar answered Sep 21 '22 07:09

Johannes Schaub - litb


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 :-)

like image 25
Alexander Gessler Avatar answered Sep 20 '22 07:09

Alexander Gessler


Take a look at the Boost Concept Check Library: http://www.boost.org/doc/libs/1_42_0/libs/concept_check/concept_check.htm

like image 6
Axel Gneiting Avatar answered Sep 19 '22 07:09

Axel Gneiting