来自模板化类的Friend函数
Friend function from a templated class
我有一个这样的类:
#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; }
// ...
};
由于Foo
的m_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
。
相关文章:
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在使用另一个类"friend"函数时无法发现错误C++
- 在运算符重载中使用带有 const 引用的 friend 函数
- 运算符重载(使用binaray friend函数)类没有成员,并且成员不可访问
- 类的 friend 函数无法访问其私有向量;
- 如何在 c++ 中使用常见的 Friend 函数
- 在Ostream Overload Friend函数中使用向量
- friend函数是如何在内部实现的
- Friend函数和未定义的私有方法
- c++ 派生基类 Friend 函数访问父级上的私有函数
- 前向声明的问题-Friend函数和行/点类
- 为什么friend函数不能访问类的私有成员
- 使用friend函数,我们可以覆盖类的私有成员吗
- Friend函数访问静态库中定义的类的私有成员
- 实现Friend函数
- Friend函数和命名空间.无法访问类中的私有成员
- 来自模板化类的Friend函数
- 使用Friend函数和operator+添加类变量并打印出来
- friend函数和include循环
- C++ Friend 函数位于单独的头文件和.cpp文件中