相当复杂(和糟糕)的标题,这就是我的意思:
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/