简体   繁体   English

具有可变参数模板和继承参数问题的递归继承

[英]Recursive inheritance with variadic templates and inherited parameter problems

If I use a chain of inheritance like the following example I could use vars from the deepest base without any problems: 如果我像下面的例子那样使用一系列继承,我可以使用来自最深基础的变量而没有任何问题:

    class A { public: int x; };
    class B : public A { };
    class C: public B { public: void Do() { cout << x << endl; } };

If I do the same with recursive variadic template classes I could not access my vars. 如果我对递归可变参数模板类执行相同操作,则无法访问我的变量。 Any idea how to access the vars and why I could not see my vars? 知道如何访问变量以及为什么我看不到我的变量?

    template <class ...Parms>
    class Example;

    template <class Head, class ...Parms>
    class Example<Head, Parms...>: public Example<Parms...>
    {
    };

    template <>
    class Example<>
    {
        public:
        int x;
    };

    template <class ...Parms>
    class Last: public Example<Parms...>
    {
        void Do() { cout << x << endl; }
    };

Compile fails before any instance of the class is instantiated! 在实例化任何类的实例之前编译失败!

x is a dependent name in this case, so you must access if as this->x (or bring it into scope by putting a using declaration in your class definition: 在这种情况下, x是一个从属名称,所以你必须访问this->x (或者通过在类定义中放入using声明将其带入范围:

using Example<Params...>::x;

EDIT 编辑

The reason for this is discussed in [temp.res] in the standard. 其原因在标准的[temp.res]中讨论过。 Basically: when the compiler is parsing your template, it sees just x . 基本上:当编译器解析你的模板时,它只看到x It has no way of knowing that x depends on the template's parameters (which it does in your case, because it comes from a base class which depends on them). 它无法知道x取决于模板的参数(在你的情况下它是这样做的,因为它来自一个依赖于它们的基类)。 Therefore, the compiler tries to resolve x using what it knows when parsing the template, and fails. 因此,编译器尝试在解析模板时使用它所知道的来解析x ,并且失败。

Writing this->x indicates that x refers to a member of the class; this->x表示x指的是该类的成员; since a base class of your particular class depends on template parameters, the compiler knows it cannot resolve x when parsing the template, and will postpone the resolution until the template is instantiated. 由于特定类的基类依赖于模板参数,因此编译器知道在解析模板时它无法解析x ,并且会推迟解析直到模板被实例化。 At that time, the template arguments are known. 那时,模板参数是已知的。

The same holds true for using Example<Params...>::x; using Example<Params...>::x; . That also tells the compiler that x depends on template parameters, and its resolution must be postponed to instanitation. 这也告诉编译器x取决于模板参数,并且其分辨率必须推迟到instanitation。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM