【发布时间】:2015-01-17 07:47:51
【问题描述】:
我正在使用 CRTP,但在访问派生类的受保护成员时遇到问题。
这是示例,接近我的代码:
template< typename Self>
class A {
public:
void foo( ) {
Self s;
s._method( s); //ERROR, because _method is protected
}
protected:
virtual void _method( const Self & b) = 0;
};
class B : public A< B> {
protected:
void _method( const B & b) {}
};
我明白了,我必须使用 friend 关键字。但我不明白把它放在 A 类的什么位置。我知道我可以在 B 中公开 void _method(const B &b),但我不想这样做。在B中使用任何关键字对我来说也是不可能的!
【问题讨论】:
-
将
friend class A<B>;放入B。 -
在 B 中使用任何关键字对我来说都是不可能的。
-
这是为什么呢?它在这里工作——coliru.stacked-crooked.com/a/954e7d10d6e1de89
-
在我的代码中,我可能不知道所有可能的推导。而且我不能命令从这个类中派生它的人给朋友。
标签: c++ friend crtp friend-function