c++ - 使用模板继承影子继承成员

标签 c++ c++11 templates inheritance

我遇到了最奇怪的错误,我不知道我做错了什么。

template <bool X>
struct A {
    int x;
};

template <bool X>
struct B : public A<X> {
    B() { x = 3; } // Error: 'x' was not declared in this scope.
};

我不明白我怎么可能看不到 x来自B ,鉴于我正在继承 A公开。

同时,这段代码编译通过:

template <bool X>
struct A {
    int x;
};

template <bool X>
struct B : public A<X> {};

int main() {
    B<false> b;
    b.x = 4;
};

我正在使用 g++ 7.0.1 进行编译。

编辑:似乎如果我引用 x 的全名,代码编译,如下所示:

B() { A<X>::x = 3; }

但是为什么呢?

最佳答案

编译器不知道如何找到x。使用 this->X 就可以了。

当编译器第一次遍历struct B时,模板参数是未知的。通过使用 this 指针,您可以将名称查找推迟到第二遍。

关于c++ - 使用模板继承影子继承成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46268613/

相关文章:

css - 用于网站开发的 Gimp vs Inkscape vs Fireworks?

c++ - Eclipse CDT 显示...未解决 ARM neon 内在函数的错误,但生成二进制文件

c++ - 如何在 C++ Linux 中执行程序

c++ - 使用递归后程序爆炸

c++ - 指向函数的模板指针的部分模板特化

javascript - 项目帮助: underscore template

c++ - 在主要 C/C++ 编译器生成的代码中注册分配规则

c++ - clang++ 3.3 静态分析器,如何消除误报?

c++ - 如何使此初始化在 C++ 中合法?

c++ - 如何仅在定义时才调用 C++11 模板中的函数