非常不平凡的模板朋友声明
very non-trivial template friend declaration
class Foo
{
template <typename T> friend void T::persist(void);
int test;
};
class Bar
{
Foo foo;
void persist(void) { foo.test = 42; } // fails
}
有了这个,我希望定义它的每个类的 persist(( 成员方法将成为 foo 的朋友。奇怪的朋友线编译,但似乎什么也没做。
提前谢谢你。
你不能那样做。您不能与所有类型的成员交朋友,并且您的模板好友声明格式不正确。中没有模板:
class Foo
{
template <typename T>
friend void T::persist(void);
int test;
};
请注意,好友声明不是模板。您可以与模板函数或类交朋友,但上面的代码中没有它们。
一个简单的解决方法是创建一个帮助程序类,从中派生并提供访问器:
class Foo {
friend class FooAccessor;
int value;
};
class FooAccessor {
protected:
void write( Foo& f, int value ) {
f.value = value;
}
};
class FooUser : private FooAccessor {
Foo f;
void persist() {
write( f, 42 );
}
};
但是您可能希望重新访问设计并寻找替代方案,请注意,使字段private
然后允许所有其他类通过friend
声明访问它们并不比仅公开字段好多少。如果你愿意解释你想要实现的目标,有人可能会帮助你。
相关文章:
- 与朋友声明相反
- 为什么即使我声明了朋友类,我也会收到错误"无法访问类中声明的私人成员"
- 为什么C++需要公共继承,忽略朋友声明,才能使动态向下工作?
- 朋友声明的复杂范围界定规则有什么意义?
- 警告定义朋友操作员在名称空间内声明
- 朋友功能声明中的错误C
- 类与朋友而不是前向声明,:哪个编译器是正确的
- Forward宣布了Singleton班级,并带有Freshial声明的朋友功能
- 在模板类中编写朋友函数声明的正确方法是什么?
- 朋友功能声明为会员函数
- 如何在两个类之外的模板类内部的非模板类中声明的朋友函数定义
- 声明一个简单模板类的variadic模板类的朋友
- 可以在C 11中有条件声明的朋友类
- 可以在C 03中有条件地声明朋友类吗?
- 我们如何在 c++ 中以朋友声明"friend elaborated-class-name ;"为例?
- 显式专用化不能是朋友声明
- 非常不平凡的模板朋友声明
- 需要帮助理解与朋友声明有关的段落
- 朋友声明:这是clang中的bug吗
- 请解释一下这个朋友声明是什么意思