c++ - 是否有一种巧妙的方法来避免覆盖模板基类的所有纯虚函数,用于多重继承

标签 c++ templates inheritance multiple-inheritance member-functions

相当复杂(和糟糕)的标题,这就是我的意思:

struct type1 {};
struct type2 {};
struct type3 {};

template< typename TYPE >
struct interface {
    virtual void f( TYPE ) = 0;
};

struct processor {
    template< typename TYPE >
    void f( TYPE ) {
        // something + for some TYPE-s have specializations, but it's irrelevant
    }
};

struct der: interface< type1 >, interface< type2 >, interface< type3 > {
    processor p;

    void f( type1 t ){ p.f( t ); }
    void f( type2 t ){ p.f( t ); }
    void f( type3 t ){ p.f( t ); }
};

是否有任何巧妙的方法来避免 der 中的所有覆盖?实际情况下,der 继承interface 10 次(模板类型不同, future 可以扩展)。当它们的主体相同时,覆盖 10 多个 f 是相当丑陋的。

processor 可以更改为任何东西,der::p 也可以是某个容器,包含一个 template-d processor

听起来我想要一个虚拟模板成员函数f,这是不允许的。

我考虑过使用宏,但我不喜欢这个主意。

编辑 注意:不幸的是,不能使用 c++11。并且不能更改不在层次结构中的 typeN 类型。

最佳答案

C++03解决方案

(请参阅 KerrekSB 对使用 C++11 功能的解决方案的回答)

您可以使用另一层继承和 CRTP 将调用分派(dispatch)给您的处理器:

template< typename TYPE, class ProcessorHolder >
struct processorDispatch : interface<TYPE> {
    virtual void f( TYPE t ) override {
        processor& p = static_cast<ProcessorHolder*>(this)->p; //CRTP --> explicit downcast
        p.f(t);
    }
};

并将其用作

struct der: processorDispatch< type1,der >, processorDispatch< type2,der >, processorDispatch< type3,der > {
    processor p;

  //make f visible - either
    using processorDispatch< type1,der >::f;
    using processorDispatch< type2,der >::f;
    using processorDispatch< type3,der >::f;
  //or
    template <typename TYPE>
    void f(TYPE t) {
      processorDispatch<TYPE, der>::f(t);
    }
}

};

Kerrek 的非 CRTP 解决方案,但通过基类链接实现“C++11-free”:

struct der_base {
  processor p;
};

template <class TYPE, class Base = der_base>
struct der_t : Base, interface<TYPE> {
  void f(TYPE t) { this->p.f(t); } 
  using Base::f;
};

template <class TYPE>
struct der_t<TYPE, der_base> : der_base, interface<TYPE> {
  void f(TYPE t) { this->p.f(t); } 
};

然后使用

typedef der_t<type1, der_t<type2, der_t<type3> > > der;

关于c++ - 是否有一种巧妙的方法来避免覆盖模板基类的所有纯虚函数,用于多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22347201/

相关文章:

c++ - 为什么在使用模板时出现 "unresolved external symbol"错误?

c++ - 是否可以编写 C++ 基类成员函数来实例化从中调用它的任何派生类?

c++ - 防止在头文件之外创建子类

c++ - 过载技巧

具有许多不同类型的 C++ 调用函数

templates - 如何从 Polymer 模板中访问自定义元素的主体?

c# - 用具体类型覆盖抽象方法

c++ - 执行一个故意在另一个程序中崩溃的程序,然后返回到原始进程

c++ - C++ 获取一天开始时间戳

c++ - 使用 GCC 编译时 C++ 中的未知结构错误