来自模板化类的Friend函数

Friend function from a templated class

本文关键字:Friend 函数      更新时间:2023-10-16

我有一个这样的类:

#include "Blarg.h"
// ...
class Foo : public Bar {    
  // ...
  static double m_value;
  // ...    
}; 

还有一个类似的:

template<class X, class Y>
class Blarg : public Bar {
  // ...
  void SetValue(double _val) { Foo::m_value = _val; }
  // ...
};

由于Foom_value是私有的(我希望保持这种状态),我想我应该将SetValue函数声明为Foo类的朋友,这样它就可以在需要时访问静态成员。

我已经在Foo的公共区域中尝试过这样的声明:

template<class X, class Y> friend void Blarg<X, Y>::SetValue(double _val);
template<class X, class Y> friend void Blarg::SetValue(double _val);
friend void Blarg::SetValue(double _val);

但在编纂方面运气不佳。如果可能的话,正确的语法是什么?

必须在Foo类之前定义Blarg类,才能将Blarg的方法之一标记为friend。是否确定Blarg是在Foo声明之前定义(或包含)的,并带有朋友行?

这似乎对我有用:

template<class X, class Y>
class Blarg : public Bar {
    public:
        void SetValue(double _val);
};
class Foo : public Bar {
    private:
        static double m_value;
    public:
        template<class X, class Y> friend void Blarg<X,Y>::SetValue(double _val);
};
template <class X, class Y>
void Blarg<X,Y>::SetValue(double _val)
{
    Foo::m_value = _val;
}

我必须通过首先定义Blarg并使SetValue不内联来打破循环依赖关系。除了缺少返回值之外,您的友元声明基本正确。

以下是正确的语法:

template<class T>
class Bla
{
 public:
  void toto(double val);
};    
class Foo {
  static double m_value;
  template<typename T>
  friend void Bla<T>::toto (double);
} ;

此外,请确保在Foo之前定义了Bla