I'm trying to find a way to make a function that is a friend to a given class. That function is another class' method and is a specialization of a template. Without specialization, I have the following compiling code in Visual Studio:
ClassA.h:
#pragma once
#include "classB.h"
class A
{
private:
int data;
void Operate();
public:
A();
~A();
template<class T> friend void B::DoSomething(const T& arg);
};
ClassB.h:
#pragma once
class B
{
private:
int data;
template<typename T> void DoSomething(const T& arg)
{
T copy = arg;
copy.Operate();
data = 3;
};
/*
template<> void DoSomething(const A& arg)
{
A copy = arg;
copy.Operate();
data = 4;
};
*/
public:
B();
~B();
};
ClassA.cpp:
#include "classA.h"
A::A()
{
data = 1;
}
A::~A()
{
}
void A::Operate()
{
data = 2;
}
ClassB.cpp:
#include "classB.h"
B::B()
{
data = 1;
}
B::~B()
{
}
How do I specialize the template and make it a friend instead of the entire template? If that is possible, where do I place it then? Do I need forward declarations anywhere? Which headers would I need to include, etc.?
I tried to uncomment the block in classB.h and add #include "classA.h"
on top of it. I also tried to replace the line template<class T> friend void B::DoSomething(const T& arg);
in classA.h with something like template<> friend void B::DoSomething(const A& arg);
. Nothing helped. It refuses to compile.
I would appreciate any insight!