给定以下两个结构,一个可以从两个嵌套的“嵌套”类派生,然后从派生对象调用foo()和bar():
struct WithNested1 {
template<class T> struct Nested {
void foo();
};
};
struct WithNested2 {
template<class T> struct Nested {
void bar();
};
};
struct Test : WithNested1::Nested<Test>,
WithNested2::Nested<Test>
{
};
Test test;
test.foo();
test.bar();
但是,如果两个外部类都作为可变参数模板参数传递,那么您将如何从它们中派生呢?
例如,这无法编译:
template<typename... Ts>
struct Test : Ts::template Nested<Test>...
{
};
Test<WithNested1, WithNested2> test;
test.foo();
test.bar();
错误:“ foo”:不是“测试”的成员
错误:“ bar”:不是“测试”的成员
奇怪的是,如果删除了对foo()和bar()的调用,它将进行编译。
template <typename... Ts>
struct Test : Ts::template Nested<Test<Ts...>>...
{
};
这是与上面相同的答案,但我想我会解释它是如何工作的。在您的示例中,首先Test
没有模板参数(编译器应警告您),但我们应该给模板参数。CRTP的目的是为您提供从您与类型相同的模板参数继承的类,这样它就可以通过模板参数访问您的方法和成员。在这种情况下,您的类型Test<Ts...>
就是您必须通过的类型。正如@aschepler指出的那样,您通常可以单独使用Test
,但是直到您已经在类中时,它才在范围内。
我认为这是一种更清洁的方式来做您想要的事情。
template <typename T>
struct A {
void bar (){
static_cast<T*>(this)->val = 3;
}
};
template <typename T>
struct B {
void foo (){
static_cast<T*>(this)->val = 90;
}
};
template <template<class> class ... Ts>
struct Test : Ts<Test<Ts...>>...
{
int val;
};
int main() {
Test<A,B> test;
test.foo();
test.bar();
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句