c++ - 使用模板化模板进行多重继承
问题描述
我想通过模板参数进行多重继承并this
在每个基类中传递对的引用,所以我可以从每个基类的方法中调用顶级对象的方法。我可以通过手动继承来做到这一点,但我希望能够通过模板参数来做到这一点。
#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();
}
推荐阅读
- python - 如何在 Python 的 for 语句中使用 if
- osgi - 跟踪整个 repo 中节点上的移动操作
- scala - Spark Checkpoint 分区无法转换为 CoGroup 分区
- python - PyQt5 错误:此应用程序无法启动,因为它无法找到或加载 Qt 平台插件“xcb”
- c++ - 在地图中使用步幅
- r - 删除列中的某些值(包含特定字符)
- jenkins - Jenkins 作业通过后,工作节点上的进程不会被杀死
- javascript - 我应该使用 mixins 还是实用程序类?
- python-3.x - 我如何使用户输入的任何其他内容都会收到错误消息,除了我的命令
- apache-spark - 从pyspark对ORC格式的Hive表执行查询时如何避免AssertionError?