I have two simple class that I made just to understand how friend class works. I am confused as to why this doesn’t compile and also would the Linear class have access to the struct inside Queues class?
Linear.h
template<typename k, typename v >
class Linear
{
public:
//Can I create a instance of Queues here if the code did compile?
private:
};
Linear.cpp
#include "Linear.h"
Queues.h
#include "Linear.h"
template<typename k, typename v >
class Linear;
template<typename x>
class Queues
{
public:
private:
struct Nodes{
int n;
};
//Does this mean I am giving Linear class access to all of my Queues class variable or is it the opposite ?
friend class Linear<k,v>;
};
Queues.cpp
#include"Queues.h"
My errors are
Queues.h:15: error: `k' was not declared in this scope
Queues.h:15: error: `v' was not declared in this scope
Queues.h:15: error: template argument 1 is invalid
Queues.h:15: error: template argument 2 is invalid
Queues.h:15: error: friend declaration does not name a class or function
To answer your initial question:
the
friendkeyword inside a class let the friend function or class access otherwise private field of the class where the friend constraint is declared.See this page for a thorough explanation of this language feature.
Regarding the compilation errors in your code:
In this line:
ask yourself, what is
k, where is it defined? Same forv.Basically, a template is not a class, it’s a syntactic construct letting you define a “class of class”, meaning that for the template:
you don’t have yet a class, but something that will let you define class if you provide it a proper typename. Within the template the typename T is defined, and can be used in place as if it were a real type.
In the following code snippets:
you define another template, which when instantiated with a given typename will contain an instance of the template C with the same typename. The typename
Uin the lineC<U> x;of the code above, is defined by the including template. However, in your code,kandvdon’t have such a definition, either in the template where they are being used, or at the top level.In the same spirit, the following template:
when instantiated, will have the instance of the class template C (again with the same parameter
U) as a friend. As far as I know, It is not possible to have class template instances be friend with a given class, for all possible parameters combinations (The C++ language doesn’t support existential types yet).You could, for instance, write something like:
to restrict the friendliness of
Linearto only the instance of that template withxandx, or something like this:If you want to allow
kandvto be defined ad lib.