如果模板是另一个模板类的子集,如何使模板类从另一个模板类派生?
假设我有两个模板类 Foo
和 Foo
。我希望前者自动从后者派生。那怎么办呢?
我这样做的动机:我想使用 Foo
和 Foo
。它们需要放置在一些基类声明中。但是,如果我将它们同质化为某个 FooBase 基类,它将丢失 FooFooBase
中将它们设为虚拟,并在 Foo
派生类中定义覆盖)。因此,如果我只使用 Foo 作为基类定义,那么一切都应该正常。下面说明了当前的问题:
struct FooBase { // Fruitless attempt to homegenize A and B defined below.
// template <int N> virtual void run() = 0; // No good, of course
};
template <typename... Ts>
struct Goo {
template <int N> void run() { } // This needs to be called by Foo<Ts...>
};
template <typename... Ts>
struct Foo : Goo<Ts...>, FooBase {
// template <int N> virtual void run() override { Goo<Ts...>::run<N>(); }
};
using A = Foo<int, char>;
using B = Foo<double, char>;
struct Thing {
FooBase *foo1, *foo2;
Thing (FooBase* f, FooBase* g) : foo1(f), foo2(g) { }
template <int N> void run() { foo1->run<N>(); foo2->run<N>(); }
};
int main() {
A* a = new A;
B* b = new B;
Thing thing(a,b);
thing.run<5>();
}
Let's say I have two template classes Foo<A,C,E>
and Foo<A,B,C,D,E,F>
. I want the former to automatically be derived from the latter. How can that be done?
My motivation for this: I want to use Foo<A,C,E>
and Foo<A,B,D>
. They need to be placed in some base class declaration. But if I homogenize them into some FooBase
base class, it will lose all the properties of Foo<Ts...>
(which has template member functions, so I cannot make them virtual in FooBase
and define the overrides in the Foo
derived classes). So if I just use Foo<A,B,C,D,E,F>
as the base class definition, then everything should work out fine. Below illustrates the problem at hand:
struct FooBase { // Fruitless attempt to homegenize A and B defined below.
// template <int N> virtual void run() = 0; // No good, of course
};
template <typename... Ts>
struct Goo {
template <int N> void run() { } // This needs to be called by Foo<Ts...>
};
template <typename... Ts>
struct Foo : Goo<Ts...>, FooBase {
// template <int N> virtual void run() override { Goo<Ts...>::run<N>(); }
};
using A = Foo<int, char>;
using B = Foo<double, char>;
struct Thing {
FooBase *foo1, *foo2;
Thing (FooBase* f, FooBase* g) : foo1(f), foo2(g) { }
template <int N> void run() { foo1->run<N>(); foo2->run<N>(); }
};
int main() {
A* a = new A;
B* b = new B;
Thing thing(a,b);
thing.run<5>();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论