Hi How can I force a template parameter T to be a subclass of a specific class Baseclass? Something like this:
template <class T : Baseclass> void function(){
T *object = new T();
}
Thanks in advance.
Hi How can I force a template parameter T to be a subclass of a specific class Baseclass? Something like this:
template <class T : Baseclass> void function(){
T *object = new T();
}
Thanks in advance.
In this case you can do:
template <class T> void function(){
Baseclass *object = new T();
}
This will not compile if T is not a subclass of Baseclass (or T is Baseclass).
By calling functions inside your template that exist in the base class.
If you try and instantiate your template with a type that does not have access to this function, you will receive a compile-time error.
You could use Boost Concept Check's BOOST_CONCEPT_REQUIRES
:
#include <boost/concept_check.hpp>
#include <boost/concept/requires.hpp>
template <class T>
BOOST_CONCEPT_REQUIRES(
((boost::Convertible<T, BaseClass>)),
(void)) function()
{
//...
}
You don't need concepts, but you can use SFINAE:
template <typename T>
boost::enable_if< boost::is_base_of<Base,T>::value >::type function() {
// This function will only be considered by the compiler if
// T actualy derived from Base
}
Note that this will instantiate the function only when the condition is met, but it will not provide a sensible error if the condition is not met.
To execute less useless code at runtime you can look at: http://www2.research.att.com/~bs/bs_faq2.html#constraints which provides some classes that perform the compile time test efficiently, and produce nicer error messages.
In particular:
template<class T, class B> struct Derived_from {
static void constraints(T* p) { B* pb = p; }
Derived_from() { void(*p)(T*) = constraints; }
};
template<class T> void function() {
Derived_from<T,Baseclass>();
}