依赖模板基础的受保护成员

Protected members of dependent template bases

本文关键字:受保护 成员 依赖      更新时间:2023-10-16

所以我通读了这个问题,我理解模板中依赖名称的前提,以及有时必须如何用this->限定方法以确保编译器可以正确找到它,但是我遇到了一个我无法弄清楚如何解决的情况。具体来说,当该方法所属的对象与*this的类型相同时,但它是不同的对象(可能属于不同的子类(。例如:

#include <iostream>
template<class T>
class A
{
protected:
virtual void foo() = 0;
};
template<class T>
class B : public A<T>
{
};
template<class T>
class C : public B<T>
{
protected:
void foo() override
{
std::cout << "Hello, world" << std::endl;
}
};
template<class T>
class D : public B<T>
{
protected:
void foo() override
{
B<T> *b = new C<T>();
b->foo(); // error: 'void A<T>::foo() [with T = int]' is protected
}
public:
void bar()
{
this->foo();
}
};
int main()
{
D<int> d;
d.bar();
}

鉴于这个继承层次结构,以及调用b->foo();时的错误,调用该函数的正确方法是什么?据我了解,原则上它应该可以通过D中的代码访问,因为它是基类的受保护成员,但它因模板系统而变得复杂。

您的问题与模板无关,如果您删除所有模板代码,则会出现相同的错误。

将成员声明为protected意味着您只能从同一(直接(类访问该成员;因此,虽然DC可能都派B,但它们都是明显不同的类型,而不是直接B,因此DC无法访问B的另一个实例的受保护成员。

例如,使用您发布的一些代码获取以下代码:

class D : public B
{
public:
void baz(D& d, B& b)
{
foo(); // ok: calls this->foo();
d.foo(); // ok: type of `d` is `D`, same class
b.foo(); // error: can't access protected member
}
};

在代码中,将B* b = new C();更改为D类中的B* b = new B();仍会遇到相同的错误,尝试访问受保护的成员。如果将其更改为D* b = new D();,则错误将消失,因为b现在与它所在的类的类型相同。

要解决此错误,您可以声明DB的 friend ,但这会带来其他需要考虑的问题,并且您必须为要访问的每个类添加一个转发/朋友声明foo

template < class T >
class D;
template <class T>
class B : public A<T>
{
friend class D<T>;
};

但是,鉴于您发布的代码,人们倾向于将bar函数移出D并将其放在B中,然后您不必使用前向声明,并且您的大部分代码保持不变:

template <class T>
class B : public A<T>
{
public:
void bar()
{
this->foo();
}
};
// Then in your D class, change the call from `foo` to `bar`
template <class T>
class D : public B<T>
{
protected:
void foo() override
{
B<T> *b = new C<T>();
b->bar();
}
};

这可能不适合您的特定方案,但最终您的问题基本上归结为需要public访问权限。

希望能有所帮助。