Reputation: 198
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!
Upvotes: 0
Views: 73
Reputation: 206697
To make B::DoSomething<int>
a friend of A
, use
friend void B::template DoSomething<int>(const int& arg);
To make B::DoSomething<A>
a friend of A
, use
friend void B::template DoSomething<A>(const A& arg);
Please note that in order to be able to do that, DoSomething
has to be a public
member of B
.
Further reading: Where and why do I have to put the "template" and "typename" keywords?
Upvotes: 2