我已经用模板化的可变列表定义了接口,以便有多个方法匹配每种类型:
template <typename T> struct IfaceElement { virtual void m(const T &) = 0; };
template <typename... Ts> struct Iface : IfaceElement<Ts>... {};
我想要实现的是有一个不同数量的Event
对象的接口。类似于:
struct A {};
struct B {};
struct Handler : Iface<A, B> {
void m(const A &) override { ... }
void m(const B &) override { ... }
}
它工作得很好。
然而,我也希望有一个实现该接口的类,它也是从可变模板元生成的。
我认为像这样的东西应该是可行的:
template <typename T> struct IfaceElement { virtual void m(const T &) = 0; };
template <typename... Ts> struct Iface : IfaceElement<Ts>... {};
template <typename T> struct ImplElement : IfaceElement<T> {
void m(const T &) override {}
};
template <typename... Ts> struct Impl : Iface<Ts...>, ImplElement<Ts>... {};
struct Z {};
struct X {};
Impl<Z, X> q;
但是我有一个编译器错误:
test.cpp:121:12: error: cannot declare variable 'q' to be of abstract type 'Impl<Z, X>'
121 | Impl<Z, X> q;
| ^
test.cpp:116:34: note: because the following virtual functions are pure within 'Impl<Z, X>':
116 | template <typename... Ts> struct Impl : Iface<Ts...>, ImplElement<Ts>... {};
| ^~~~
test.cpp:110:58: note: 'void IfaceElement<T>::m(const T&) [with T = X]'
110 | template <typename T> struct IfaceElement { virtual void m(const T &) = 0; };
| ^
test.cpp:110:58: note: 'void IfaceElement<T>::m(const T&) [with T = Z]'
我的ImplElement
实现似乎与IfaceElement
纯方法不匹配。
你知道我该怎么解决这个问题吗?
发布于 2020-03-30 06:25:18
我已经明白了这一点,需要虚拟继承来匹配这些接口。
编译代码:
template <typename T> struct IfaceElement { virtual void m(const T &) = 0; };
template <typename... Ts> struct Iface : virtual IfaceElement<Ts>... {};
template <typename T> struct ImplElement : virtual IfaceElement<T> {
void m(const T &) override {}
};
template <typename... Ts> struct Impl : Iface<Ts...>, ImplElement<Ts>... {};
struct Z {};
struct X {};
Impl<Z, X> q;
发布于 2020-03-30 07:12:29
您从IfaceElement
继承了2次。一次通过ImplElement
,一次通过Iface
。
这意味着
template <typename... Ts> struct Impl : Iface<Ts...>, ImplElement<Ts>... {};
每个Ts
将有两个相同的IfaceElement
。
您可以通过使用虚拟继承来创建它,但是为什么需要从同一基址继承两次呢?
template <typename... Ts> struct Impl : ImplElement<Ts>... {};
也将在每个Ts
中只工作一次并从IfaceElement
继承。
https://stackoverflow.com/questions/60925106
复制相似问题