代码之家  ›  专栏  ›  技术社区  ›  Juliano

模板内的继承-公共成员变为不可见?

  •  0
  • Juliano  · 技术社区  · 14 年前

    我尝试在类模板(内部类)内定义的类之间使用继承。但是,编译器(gcc)拒绝授予我访问基类中公共成员的权限。

    示例代码:

    template <int D>
    struct Space {
        struct Plane {
            Plane(Space& b);
            virtual int& at(int y, int z) = 0;
            Space& space;             /* <= this member is public */
        };
    
        struct PlaneX: public Plane {
            /* using Plane::space; */
            PlaneX(Space& b, int x);
            int& at(int y, int z);
            const int cx;
        };
    
        int& at(int x, int y, int z);
    };
    
    template <int D>
    int& Space<D>::PlaneX::at(int y, int z) {
        return space.at(cx, y, z);  /* <= but it fails here */
    };
    
    Space<4> sp4;
    

    编译器说:

    file.cpp: In member function ‘int& Space::PlaneX::at(int, int)’:
    file.cpp:21: error: ‘space’ was not declared in this scope
    

    如果 using Plane::space; 添加到类planex的定义中,或者如果通过 this 指针,或者如果类空间更改为非模板类,那么编译器可以使用它。

    我不知道这是不是一个模糊的C++限制,还是GCC中的一个错误(GCC版本4.4.1和4.4.3测试)。有人有主意吗?

    1 回复  |  直到 14 年前
        1
  •  1
  •   Baiyan Huang    14 年前

    它应该是一个与C++的两阶段名称查找有关的问题:

    http://gcc.gnu.org/onlinedocs/gcc-4.4.3/gcc/Name-lookup.html#Name-lookup