norman
norman

Reputation: 5586

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?

Upvotes: 9

Views: 228

Answers (3)

Patrik Beck
Patrik Beck

Reputation: 2505

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.

Upvotes: 3

Xaqq
Xaqq

Reputation: 4396

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.

Upvotes: 0

Jan Spurny
Jan Spurny

Reputation: 5537

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?

Upvotes: 7

Related Questions