如果模板是另一个模板类的子集,如何使模板类从另一个模板类派生?

发布于 2025-01-15 10:56:24 字数 1270 浏览 2 评论 0原文

假设我有两个模板类 FooFoo。我希望前者自动从后者派生。那怎么办呢?

我这样做的动机:我想使用 FooFoo。它们需要放置在一些基类声明中。但是,如果我将它们同质化为某个 FooBase 基类,它将丢失 Foo的所有属性(它具有模板成员函数,所以我不能在 FooBase 中将它们设为虚拟,并在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文