I have the following template class and template function which intends to access the class\' private data member:
#include
template
The simplest option is to define the friend within the class:
template
class MyVar
{
int x;
friend void printVar(const MyVar & var) {
std::cout << var.x << std::endl;
}
friend void scanVar(MyVar & var) {
std::cin >> var.x;
}
};
The downside is that the functions can only be called through argument-dependent lookup. That's not a problem in your example, but might be a problem if they don't have a suitable argument, or you want to specify the name without calling it.
If you want a separate definition, then the template will have to be declared before the class definition (so it's available for a friend declaration), but defined afterwards (so it can access the class members). The class will also have to be declared before the function. This is a bit messy, so I'll only show one of the two functions:
template class MyVar;
template void printVar(const MyVar & var);
template
class MyVar
{
int x;
friend void printVar(const MyVar & var);
};
template void printVar(const MyVar & var) {
std::cout << var.x << std::endl;
}