I have a class like this:
#include "Blarg.h"
// ...
class Foo : public Bar {
// ...
static double m_value;
// ...
};
And another one like this:
template<class X, class Y>
class Blarg : public Bar {
// ...
void SetValue(double _val) { Foo::m_value = _val; }
// ...
};
Since Foo
's m_value
is private (and I would like to keep it that way), I thought I would declare the SetValue
function as a friend to the Foo
class so that it could access the static member when needed.
I've tried declarations along these lines within Foo
's public area:
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);
...but no luck in compiling. What is the proper syntax for this, if possible?
You have to define Blarg
class before Foo
class in order to mark one of Blarg
's method as a friend
. Are sure the Blarg
is defined (or included) before Foo
declaration with a friend line?
This seems to work for me:
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;
}
I had to break the circular dependency by defining Blarg first and making SetValue not inline. Your friend declaration was pretty much correct, except for the missing return value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With