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?
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; };
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With