c++ - 是否可以使用 C++ 中类似 mixin 的模式覆盖功能

标签 c++ templates

假设我有以下类(class):

class Base {
public:
    virtual int do_something() = 0;
protected:
    virtual int give_intermediate_result(int) = 0;

    int m_some_shared_resources;
};

class Foo : public Base {
public:
    virtual int do_something() override { return give_intermediate_result(1); }
protected:
    virtual int give_intermediate_result(int a) override { return a*2; }
};

// and something like this:
class FooMixinA : public virtual Base {
protected:
    virtual int give_intermediate_result(int) override;
};

class FooMixinB : public virtual Base {
public:
    virtual int do_something() override;
};

我想做的是这样的:

Foo<FooMixinA, FooMixinB> myfoo (...);

基本上应该用 FooMixinB 覆盖 Foo 的 do_something 实现,并用 FooMixinA 覆盖 give_intermediate_result >。另外,我希望 mixins 能够替换其他 mixins 功能,即。 e. mixin 的顺序很重要,因为一个 mixin 可能会使用另一个 mixin(例如其get_intermediate_result)。 同时,他们都应该有权访问某些共享的底层资源。

我可以做类似的事情吗?如果可以的话我会如何处理它?<​​/p>

最佳答案

template<class Base, template<class>class...Mixins>
struct Foo:Base{};
template<class Base, template<class>class M0, template<class>class...Mixins>
struct Foo<Base, M0, Mixins...>:M0<Foo<Base, Mixins...>>{};

struct Base{
  virtual int A()=0;
  virtual int B()=0;
  virtual ~Base()=default;
};

template<class Base>
struct MixinA:Base{
  int A() final{ return 3; }
};
template<class Base>
struct MixinB:Base{
  int B() override{ return -1; }
};
template<class Base>
struct MixinB2:Base{
  int B() final{ return 0; }
};

using Bob=Foo<Base, MixinA, MixinB2, MixinB>;

std::unique_ptr<Base> pBase=std::make_unique<Bob>();
std::cout << pBase->A() << pBase->B() <<'\n';

最左边的 mixins 会覆盖最右边的 mixin。

反之亦然

template<class Base, template<class>class M0, template<class>class...Mixins>
struct Foo<Base, M0, Mixins...>:Foo<M0<Base>, Mixins...>{};

如果您确实愿意,我们可以删除 FooBase 参数。对于从右到左的应用程序:

template<template<class>class...Mixins>
struct Foo:Base{};
template<template<class>class M0, template<class>class...Mixins>
struct Foo<M0, Mixins...>:M0<Foo<Mixins...>>{};

这很容易。对于从左到右,您需要变得更漂亮。

关于c++ - 是否可以使用 C++ 中类似 mixin 的模式覆盖功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66045268/

相关文章:

c++ - 错误与 'operator=' 不匹配(操作数类型为 'Person' 和 'Person*' )

c++ - 第 n 个元素的算法

css - 如何更改 CSS 模板中的列顺序以将重要内容放在前面?

c++ - 如何在 C++ 中根据函数模板类型应用不同的#define?

c++ - 线程中的QT QTcpServer;如何在退出时关闭监听服务器?

c++ - 像素距离泛光填充

c++ - 指针和函数的部分特化

c++ - 如何使自定义图形适合 boost 图形库模板?

c++ - typename参数包和auto参数包的区别?

c++ - QStyledItemDelegate中如何根据qStylesheet进行绘画