【发布时间】:2018-12-15 01:04:42
【问题描述】:
假设我必须遵循层次结构:
template<class T> class Base {
protected:
T container;
};
template<class T> class Derived1 : public Base<T> {
public:
void f1() {
/* Does stuff with Base<T>::container */
}
};
template<class T> class Derived2 : public Base<T> {
public:
void f2() {
/* Does stuff with Base<T>::container */
}
};
现在我想要一个独立的类(不是从 Base 派生的),它可以直接从 Base 或任何派生类访问 Base<T>::container。我阅读了模板朋友类,这似乎是我的问题的解决方案,但我还无法弄清楚语法。
我正在寻找类似的东西:
template<class T> class Foo{
template<T> friend class Base<T>; // <-- this does not work
public:
size_t bar(const Base<T> &b) const{
return b.container.size();
}
};
Derived1<std::vector<int> > d;
d.f1();
Foo<std::vector<int> > foo;
size_t s = foo.bar()
friend 类行 导致error: specialization of ‘template<class T> class Base’ must appear at namespace scope template<T> friend class Base<T> 并且成员变量container 仍然无法访问。
【问题讨论】:
-
那里不需要
template<T>。 -
而
friend则以另一种方式完成:Base可以授予访问权限。Foo不能假装是Base的朋友。 -
显然我的思维方式有两个重大错误。首先,在错误的位置声明朋友类,其次,在朋友类之后放置一个(在我的情况下)不必要的模板参数。非常感谢@aschepler 的全面回答。还要感谢 Dmytro Dadyka,链接讨论的评分最高的答案也很有帮助。
标签: c++ templates inheritance friend-class