简体   繁体   中英

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!

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

You can try a templated constructor as follows:

#include <iostream>

using namespace std;

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;
    }
};

template <class Parent>
class Child
: public Parent {

public:
    template <class... Args>
    Child(Args... args)
    : Parent(args...) {

    }
};

int main() {
    Child<A> a_child(42);
    Child<B> b_child("42");
    a_child.test();
    b_child.test();
}

You can use a delegating constructor if you want to let the user decides the parameters:

template <class ParentClass>
class Child : public ParentClass {
public:
    using ParentClass::ParentClass;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM