the_bearded_skull the_bearded_skull - 2 months ago 6
C++ Question

C++: Inheriting from template class with possible varying constructor arguments

Suppose we have the following sample classes:

class A {
public:
explicit A(int foo) { }

void test() {
cout << "I'm in A" << endl;
}
};

class B {
public:
explicit B(string bar) { }

void test() {
cout << "I'm in B" << endl;
}
};


I would like to define a child class to inherit from a templatized class that
could be specialized as one of either A or B. The problem I'm facing is that A
and B have different constructor arguments, so building Child's constructor is
proving to be a bit vexing. Things work if I do something like the following:

template <class ParentClass>
class Child : public ParentClass {
public:
Child<B>() : ParentClass("foo") {
}
};

int main() {
Child<B> c;
c.test();
return 0;
}


However, I'd like to also be able to do something like
Child<A> c
. Is this
possible?

Thanks!

Answer

You may specialize for each class:

template <class ParentClass>
class Child : public ParentClass {
  public:
    Child();
};

template <>
Child<A>::Child() : A(42) {}

template <>
Child<B>::Child() : B("42") {}

Demo

Comments