9

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?

norman
  • 5,128
  • 13
  • 44
  • 75

3 Answers3

7

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?

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
Jan Spurny
  • 5,219
  • 1
  • 33
  • 47
3

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.

Patrik Beck
  • 2,455
  • 1
  • 19
  • 24
0

Here is the correct syntax:

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);
} ;

Also, make sure that Bla is defined before Foo.

Xaqq
  • 4,308
  • 2
  • 25
  • 38