我想通过模板参数进行多重继承并将引用传递给 this
在每个基类中,因此我可以从每个基类的方法中调用顶级对象的方法。我可以通过手动继承来完成此操作,但我希望能够通过模板参数来完成此操作。
Godbolt link with manual inheritance
#include <cstdio>
template <typename T>
struct Foo {
Foo(T &t)
: t_(t) {
}
void foo() {
t_.call("foo");
}
T &t_;
};
template <typename T>
struct Bar {
Bar(T &t)
: t_(t) {
}
void bar() {
t_.call("bar");
}
T &t_;
};
template <template<typename> typename... Methods>
struct Impl : public Methods<Impl>... {
Impl()
: Methods<Impl>(*this)... {
}
void call(const char *m) {
printf(m);
}
};
int main() {
auto t = Impl<Foo, Bar>();
t.foo();
t.bar();
}
我尝试过这种方法,但它给出了
type/value mismatch at argument 1 in template parameter list for 'template<class> class ... Methods'
最佳答案
感谢 @Nicol Bolas,他建议为此使用 static_cast
和 CRTP
#include <cstdio>
template <typename T>
struct Foo {
void foo() {
static_cast<T*>(this)->call("foo");
}
};
template <typename T>
struct Bar {
void bar() {
static_cast<T*>(this)->call("bar");
}
};
template <template<typename> typename... Methods>
struct Impl : public Methods<Impl<Methods...>>... {
Impl() {
}
void call(const char *m) {
printf(m);
}
};
int main() {
auto t = Impl<Foo, Bar>();
t.foo();
t.bar();
}
关于c++ - 使用模板化模板的多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66927346/