非常不平凡的模板朋友声明

very non-trivial template friend declaration

本文关键字:朋友 声明 不平凡 非常      更新时间:2023-10-16
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声明访问它们并不比仅公开字段好多少。如果你愿意解释你想要实现的目标,有人可能会帮助你。