Force template argument to derive from a given class

Provided the following template:

1
2
3
4
5
6
7
8
template <class T>
class MyTemplate {
	private:
		T myData;
	public:
		MyTemplate(const T &data) : myData(data) {}
		bool Contains(const T &);
};


Is there a way to ensure at compile time that the argument T derives from another class?

I want T to derive from my abstract class Comparable, so that it implements CompareTo and I can call that method from Contains (and other methods) instead of using operators (== < >) which T would have to overload.

I provided the simplest example of MyTemplate, which would make more sense if it where, for example, a linked list (so Contains traverses it and calls CompareTo for each element).

Thanks.
I'm not sure of a way to do it, but doing it would be more work than it's worth. I'd say just assume T is derived from that class and call myData.CompareTo(). If T wasn't derived from Comparable (or at least if it doesn't have a CompareTo function), then you'll get the desired compiler error.
Last edited on
There is a very clean way to do this using the Boost Concept Check Library: http://www.boost.org/doc/libs/1_38_0/libs/concept_check/concept_check.htm

This feature will be in the next version of the C++ standard.
Topic archived. No new replies allowed.