c++ - 基模板类数据成员在派生模板类中不可见?

标签 c++ templates inheritance base-class

考虑以下 C++ 代码,

template <typename Derived>
struct A
{
    bool usable_;
};

template <typename Derived>
struct B : A< B<Derived> >
{
    void foo()
    {
        usable_ = false;
    }
};

struct C : B<C>
{
    void foo()
    {
        usable_ = true;
    }
};

int main()
{
    C c;
}

我遇到编译错误:在成员函数中 void B<Derived>::foo() :

template_inherit.cpp:12: error: 'usable_' was not declared in this scope.

这是为什么呢?有什么好的解决方法吗?

最佳答案

那是因为usable_是一个非依赖的名字,所以在解析模板时查找,而不是在实例化时(基类已知时)查找。

非限定名称查找将不会查找,并且从不在依赖基类中查找非依赖名称。您可以使名称 usable_ 依赖如下,这也将摆脱不合格的名称查找

this->usable_ = false;

// equivalent to: A<B>::usable_ = false;
A< B<Derived> >::usable_ = false;

B::usable_ = false;

所有这些都会起作用。或者您可以使用 using 声明在派生类中声明名称

template <typename Derived>
struct B : A< B<Derived> >
{
    using A< B<Derived> >::usable_;

    void foo()
    {
        usable_ = false;
    }
};

请注意,在 C 中不会有问题 - 它只会影响 B

关于c++ - 基模板类数据成员在派生模板类中不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4210108/

相关文章:

c++ - 如何在 gdb 中转储 STL 容器数据?

WPF ErrorTemplate 未聚焦时可见?

C++ 模板偏特化 - 只特化一个成员函数

c++ - 访问者模式与具有输入类型限制的向下转型

c++ - POCO HTTPS 请求验证服务器证书

c++ - 增加 mpi 中的 CPU 数量会增加处理时间?

c++ - 打印返回的迭代器

java - 在 Java 中创建子类来更改注释是否被认为是不好的做法?

c++ - 类模板继承 C++

java - 私有(private)字段是否被子类继承?