...

/

Understanding Friendship in Templates

Understanding Friendship in Templates

Take your knowledge of templates to the next level by building a friend function within them.

When we define a class, we can restrict access to its member data and member functions with the protected and private access specifiers. If a member is private, it can only be accessed within the class. If a member is protected, it can be accessed from derived classes with public or protected access. However, a class can grant access to its private or protected members to other functions or classes with the help of the friend keyword. These functions or classes, to which special access has been granted, are called friends. Let’s take a look at a simple example:

Press + to interact
struct wrapper
{
wrapper(int const v) :value(v) {}
private:
int value;
friend void print(wrapper const & w);
};
void print(wrapper const& w)
{ std::cout << w.value << '\n'; }
int main(){
wrapper w{ 42 };
print(w);
}

The wrapper class has a private data member called value. There’s a free function called print that takes an argument of the type wrapper and prints the wrapped value to the console. However, in order to be able to access it, the function is declared a friend of the wrapper class.

Friendship in the context of templates

We won’t focus on the way friendship works for nontemplates. We should be familiar with this feature to proceed to discuss it in the context of templates. When it comes to templates, things get a bit complicated. ...