sop
sop

Reputation: 3625

Is there a way of defining a template on an existing type?

I have a class ClassType that is a parent for some other classes. I want to create a template that can only have the ClassType (and its children) type, like:

template< ClassType > class ClassABC
{
   std::shared_ptr< ClassType > m_member;
   // ...
public:
   ClassABC< ClassType >(std::shared_ptr< ClassType >& objIn) : m_member(objIn) {}
   void foo( int v1, int v2); // the function does an operation general to ClassType
}

But it is not correct. Is there a way to do it?


I want to have some kind of specializations like:

template<> class ClassABC< B >
{
   std::shared_ptr< B > m_member;
   // ...
public:
   ClassABC< B >(std::shared_ptr< B >& objIn) : m_member(objIn) {}
   void foo( int v1, int v2); // the function does some operation specific to B
}

and for the other classes (A and C) it does the generic operation.

Upvotes: 0

Views: 72

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145239

You can use std::enable_if in conjunction with std::is_base_of.

For example,

#include <type_traits>      // std::is_base, std::enable_if

using std::enable_if;
using std::is_base_of;

class Base {};

template<
    class Type,
    class Enabled = typename enable_if< is_base_of<Base, Type>::value, void >::type
    >
class ClassABC
{
public:
    void foo() {}
};

class A: public Base {};
class B: public Base {};
class X {};

using At = ClassABC<A>;
using Bt = ClassABC<B>;
using Ct = ClassABC<Base>; 

using Xt = ClassABC<X>;  //! Nope.

auto main() -> int
{}

Upvotes: 3

Related Questions