我有一个钻石继承计划,其中最后一个孩子应该能够从许多不同的父母那里继承下来。
A
/|\
/ | \
B C ...
| | |
* *
D E
现在,假设我有一个class D : public B
,,class E : public B, public C
等等。D
我想从其所有父项中调用相同的函数,由于继承,我保证该函数存在。我的想法是我可以将其包装在可变参数的模板中。
目前我有这个:
template <typename T>
class A
{
public:
A(T t) : mT(t) {}
virtual ~A() {}
virtual void doThings() = 0;
protected:
T mT;
};
template <typename T, typename A = A<T>>
class B : public A
{
public:
B(T t) : A(t) {}
virtual ~B() {}
virtual void doThings() { std::cout << "B" << std::endl; }
};
template <typename T, typename A = A<T>>
class C : public A
{
public:
C(T t) : A(t) {}
virtual ~C() {}
virtual void doThings() { std::cout << "C" << std::endl; }
};
现在我想我可以做这样的事情,但是显然行不通:
template <typename T, typename ...Args>
class ChildGenerator : public Args...
{
public:
ChildGenerator(T t) : Args(t)... {}
// The unpacking of the variadic template does not work here.
// Do I need to make it recursive somehow? How can I do that without having to instantiate new classes B and C?
void doThings() override { Args...::doThings();}
};
我希望我可以这样使用它:
int main()
{
using B = B<double>;
using C = C<double>;
B c1(0.0);
C c2(1.0);
ChildGenerator<double, B, C> c3(2.0);
c1.doThings();
c2.doThings();
c3.doThings();
}
预期输出(顺序无关紧要):
B
C
B // <-- order of these two does not matter
C // <--
我正在努力实现的目标有可能吗?
遍历可变参数基数的一种方法:
template <typename T, typename ...Args>
class ChildGenerator : public Args...
{
public:
ChildGenerator(T t) : Args(t)... {}
void doThings() override {
int dummy[] = {0, (Args::doThings(), void(), 0)...};
static_cast<void>(dummy); // avoid warning for unused variable
}
};
或在C ++ 17中,带有折叠表达式:
void doThings() override {
(static_cast<void>(Args::doThings()), ...);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句