An issue that I've run into a couple of times now is that when using a template class I've wanted it to encapsulate another class, using it for a number of operations. This isn't really a big deal, because any class that actually implements functions named what I call will work.
The problem is that this makes me a little nervous, it's not really all that type safe. Sure, it'll probably work for most cases, and generally you only want a functor anyway, but in those few, rare cases where you want to ensure that a template parameter inherits from a particular class, here is an easy method (this is my first time posting code, hopefully it comes out well).
Basically what you want to do is define a variable of the template parameter type, then create a do nothing function, probably private so it won't clutter the public namespace that takes, as a parameter a reference to the class that you want to use as a base class. Then just call that function at the top of each constructor, and pass in your class variable. If the class variable is the wrong type, the user will get an error to that effect, it won't be quite as neat as a template error, but it will help a lot.
For example: (this should be fully compilable and executable in it's current form)
class NonThing
{
public:
NonThing()
{
}
virtual ~NonThing()
{
}
};
class Thing
{
public:
Thing()
{
}
virtual ~Thing()
{
}
};
class SubThing1 : public Thing
{
public:
SubThing1()
{
}
virtual ~SubThing1()
{
}
};
class SubThing2 : public Thing
{
public:
SubThing2()
{
}
virtual ~SubThing2()
{
}
};
template<class subt>
class Base
{
public:
Base()
{
validatething( xThing );
}
virtual ~Base()
{
}
void validatething( Thing & ) { }
subt xThing;
};
int main()
{
// These are all fine
Base<Thing> bThing;
Base<SubThing1> bSubThing1;
Base<SubThing2> bSubThing2;
// This will fail with a compile time error
//Base<NonThing> bNonThing;
}