简体   繁体   English

c ++从专门的模板类继承

[英]c++ inherit from specialized template class

template<typename T1, typename T2, typename T3>
class A: public A<T1, T2, void> {
public:
    T1 a;
    T2 b;
    T3 c;

    void set() { a = aa; } // Cannot find variable `aa' here!
};

template<typename T1, typename T2>
class A<T1, T2, void> {
public:
    T1 aa;
    T2 bb;
};

As above, I have a template class A , and its partial specialized form A' . 如上所述,我有一个模板类A及其部分专用形式A' So is it possible for A to inherit from A'? 那么A可以从A'继承吗? According to g++, it seems OK. 根据g ++,看来还可以。 However, when I tried to access members in A', g++ started to complain: Fail to find that symbol. 但是,当我尝试访问A'中的成员时,g ++开始抱怨:找不到该符号。 Anybody knows why? 有人知道为什么吗?

As far as I remember you have to pull in aa to derived class with 'using'. 据我记得,您必须使用“ using”将aa引入派生类。 Add the following (I do not remember exact syntax so forgive me any compilation issues) to your generic template: 将以下内容(我不记得确切的语法,因此请原谅任何编译问题)添加到您的通用模板中:

using A<T1, T2, void>::aa;

EDIT: As Mehrdad noted this->aa should also work. 编辑:正如Mehrdad指出,this-> aa也应该起作用。

The name look up rules with C++ templates may seem a bit non-intuitive. 使用C ++模板的名称查找规则似乎有点不直观。 When the compiler first parses the template definition, it resolves all names, which are not template-argument dependent . 编译器首次解析模板定义时,它将解析不依赖模板参数的所有名称。 When it comes to template instantiation, it will resolve the rest. 当涉及模板实例化时,它将解决其余问题。

If you take a look at the definition of class A only, there is no obvious dependence of the symbol aa on type arguments T1, T2 or T3. 如果仅查看类A的定义,则符号aa对类型参数T1,T2或T3的依赖性不明显。 So the compiler tries to resolve the name, but it cannot, since that name is undefined in that environment. 因此,编译器将尝试解析该名称,但无法解析,因为该名称在该环境中未定义。

So, to convince the compiler to do what you wanted, you have to use of the tricks below: 因此,要说服编译器执行您想要的操作,必须使用以下技巧:

  • The easiest is probably this->aa . 最简单的方法可能是this-> aa Since this has a template-argument dependent superclass, its members can only be looked up at template instantiation time, so everything is fine. 由于具有依赖模板参数的超类,因此只能在模板实例化时查找其成员,因此一切都很好。

  • Qualify the member with the superclass, ie use A<T1, T2, void>::aa . 使用超类来限定成员,即使用A <T1,T2,void> :: aa This makes the dependency really obvious. 这使得依赖性非常明显。 You may also use the using directive, so that so do not have to type this every time. 您也可以使用using指令,这样就不必每次都键入此指令。

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

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