gpt4 book ai didi

c++ - 模板化模板的多重继承

转载 作者:行者123 更新时间:2023-12-04 07:51:52 25 4
gpt4 key购买 nike

我想通过模板参数进行多重继承并将引用传递给 this在每个基类中,所以我可以从每个基类的方法调用顶级对象的方法。我可以通过手动继承来做到这一点,但我希望能够通过模板参数来做到这一点。
Godbolt link
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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com