Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Friend function from a templated class

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?

like image 341
norman Avatar asked Jul 30 '13 14:07

norman


2 Answers

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?

like image 189
Jan Spurny Avatar answered Nov 08 '22 13:11

Jan Spurny


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.

like image 3
Patrik Beck Avatar answered Nov 08 '22 14:11

Patrik Beck