[英]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. 我想定义一个子类,以从可以专门化为A或B之一的模板化类继承。我面临的问题是A和B具有不同的构造函数参数,因此证明构造Child的构造函数是有点烦人。 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
. 但是,我也想做类似
Child<A> c
事情。 Is this possible? 这可能吗?
Thanks! 谢谢!
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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.