Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class template of specific baseclass

Let's say I have the classes:

class Base{};  class A: public Base{     int i; };  class B:public Base{     bool b; }; 

And now I want to define a templated class:

template < typename T1, typename T2 > class BasePair{     T1 first;     T2 second; }; 

But I want to define it such that only decendants of class Base can be used as templateparameters.

How can I do that?

like image 901
Mat Avatar asked Jan 06 '10 12:01

Mat


2 Answers

C++11 introduces <type_traits>

template <typename T1, typename T2> class BasePair{ static_assert(std::is_base_of<Base, T1>::value, "T1 must derive from Base"); static_assert(std::is_base_of<Base, T2>::value, "T2 must derive from Base");      T1 first;     T2 second; }; 
like image 172
Hashbrown Avatar answered Oct 04 '22 20:10

Hashbrown


More exactly:

class B {}; class D1 : public B {}; class D2 : public B {}; class U {};  template <class X, class Y> class P {     X x;     Y y; public:     P() {         (void)static_cast<B*>((X*)0);         (void)static_cast<B*>((Y*)0);     } };  int main() {     P<D1, D2> ok;     P<U, U> nok; //error } 
like image 32
user213546 Avatar answered Oct 04 '22 20:10

user213546