I have the following template class and template function which intends to access the class\' private data member:
#include
template
I managed to get the following work
#include
template
class MyVar;
template
void printVar(const MyVar& var);
template
void scanVar(MyVar& var);
template
class MyVar
{
int x;
friend void printVar(const MyVar& var);
friend void scanVar(MyVar& var);
};
template
void printVar(const MyVar& var)
{
std::cout << var.x << std::endl;
}
template
void scanVar(MyVar& var)
{
std::cin >> var.x;
}
struct Foo {};
int main(void)
{
MyVar a;
scanVar(a);
printVar(a);
return 0;
}
UPD: http://en.cppreference.com/w/cpp/language/friend talks about a similar case with operators under "Template friend operators":
A common use case for template friends is declaration of a non-member operator overload that acts on a class template, e.g.
operator<<(std::ostream&, const Foo
for some user-defined&) Foo
Such operator can be defined in the class body, which has the effect of generating a separate non-template
operator<<
for eachT
and makes that non-templateoperator<<
a friend of itsFoo
...
or the function template has to be declared as a template before the class body, in which case the friend declaration within
Foo
can refer to the full specialization ofoperator<<
for itsT