c – 如何从可变参数模板参数的嵌套类派生?
发布时间:2020-12-16 09:48:39 所属栏目:百科 来源:网络整理
导读:给定以下两个结构,可以从嵌套的“嵌套”类派生,并从派生对象调用foo()和bar(): struct WithNested1 { templateclass T struct Nested { void foo(); };};struct WithNested2 { templateclass T struct Nested { void bar(); };};struct Test : WithNested1:
给定以下两个结构,可以从嵌套的“嵌套”类派生,并从派生对象调用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()的调用,它会编译. 解决方法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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |