Template class and Friend template function - c++

C++ Primer: Template and Functioins
template <typename>
class BlobPtr;
template <typename>
class Blob;
template <typename T>
bool operator==(const Blob<T>&, const Blob<T>&);
template <typename T>
class Blob
{
friend class BlobPtr<T>;
friend bool operator==<T>(const Blob<T>&, const Blob<T>&);
};
Then:
Blob<char> ca;
Blob<int> ia;
The members of BlobPtr<char> may access the nonpublic parts of ca (or any
other Blob object), but ca has no special access to ia (or any other
Blob) or to any other instantiation of Blob.
Question:
I'd like to test the code. How can I access the nonpublic parts of ia with ca? To clarify, I know it's not possible, but I'd like to test the code to see the error.

You can just add template before using friend.
template<typename T>
class Blob
{
template<typename T1>
friend class Blob;
public:
template<typename T1>
bool operator==(const Blob<T1>& other)
{
return i == other.i;
}
private:
T i;
};
Blob<int> i;
Blob<char> j;
int main()
{
i == j;
}
Adding template makes every Blob<T> class into a friend class of each other. So, every member function of Blob<int> can access to private members of Blob<char> and vice versa.

Related

In C++ can one friend a template class in a non template class for ALL specializations of the template class? [duplicate]

Let's say I'm creating a class for a binary tree, BT, and I have a class which describes an element of the tree, BE, something like
template<class T> class BE {
T *data;
BE *l, *r;
public:
...
template<class U> friend class BT;
};
template<class T> class BT {
BE<T> *root;
public:
...
private:
...
};
This appears to work; however I have questions about what's going on underneath.
I originally tried to declare the friend as
template<class T> friend class BT;
however it appears necessary to use U (or something other than T) here, why is this? Does it imply that any particular BT is friend to any particular BE class?
The IBM page on templates and friends has examples of different type of friend relationships for functions but not classes (and guessing a syntax hasn't converged on the solution yet). I would prefer to understand how to get the specifications correct for the type of friend relationship I wish to define.
template<class T> class BE{
template<class T> friend class BT;
};
Is not allowed because template parameters cannot shadow each other. Nested templates must have different template parameter names.
template<typename T>
struct foo {
template<typename U>
friend class bar;
};
This means that bar is a friend of foo regardless of bar's template arguments. bar<char>, bar<int>, bar<float>, and any other bar would be friends of foo<char>.
template<typename T>
struct foo {
friend class bar<T>;
};
This means that bar is a friend of foo when bar's template argument matches foo's. Only bar<char> would be a friend of foo<char>.
In your case, friend class bar<T>; should be sufficient.
In order to befriend another same-type struct:
#include <iostream>
template<typename T_>
struct Foo
{
// Without this next line source.value_ later would be inaccessible.
template<typename> friend struct Foo;
Foo(T_ value) : value_(value) {}
template <typename AltT>
void display(AltT &&source) const
{
std::cout << "My value is " << value_ << " and my friend's value is " << source.value_ << ".\n";
}
protected:
T_ value_;
};
int main()
{
Foo<int> foo1(5);
Foo<std::string> foo2("banana");
foo1.display(foo2);
return 0;
}
With the output as follows:
My value is 5 and my friend's value is banana.
In template<typename> friend struct Foo; you shouldn't write T after typename/class otherwise it will cause a template param shadowing error.
It's not necessary to name the parameters so you get fewer points of failure if refactoring:
template <typename _KeyT, typename _ValueT> class hash_map_iterator{
template <typename, typename, int> friend class hash_map;
...
The best way to make a template class a friend of a template class is the following:
#include <iostream>
using namespace std;
template<typename T>
class B;
template<typename T>
class A
{
friend class B<T>;
private:
int height;
public:
A()//constructor
A(T val) //overloaded constructor
};
template<typename T>
class B
{
private:
...
public:
B()//constructor
B(T val) //overloaded constructor
};
In my case this solution works correctly:
template <typename T>
class DerivedClass1 : public BaseClass1 {
template<class T> friend class DerivedClass2;
private:
int a;
};
template <typename T>
class DerivedClass2 : public BaseClass1 {
void method() { this->i;}
};
I hope it will be helpful.

Template Friend Function / Class forward declaration

Why do we need template forward declaration for BlobPtr and operator overloading for template.
template <typename> class BlobPtr;
template <typename> class Blob;
template <typename T>
bool operator==(const Blob<T>&, const Blob<T>&);
template <typename T>
class Blob {
friend class BlobPtr<T>;
friend bool operator==<T>
(const Blob<T>&, const Blob<T>&);
};
class BlobPtr<T>{};
Blob<char> ca;
Blob<int> ia;
For for nontemplate class, forward declaration is not needed.
class Blob {
type
class BlobPtr;
friend bool operator==
(const Blob&, const Blob&);
};
class BlobPtr{};
If you want to declare the template in a friend declaration, you can just do that, you don't need forward declarations:
template <typename T>
class Blob {
template <typename U>
friend class BlobPtr;
template <typename U>
friend bool operator==(const Blob<U>&, const Blob<U>&);
};
This declares all instances of the templates as friends, not just the matching one. That is, BlobPtr<int> and BlobPtr<long> (and generally BlobPtr<Anything>) are all friends of Blob<int>.
If you want to declare a particular specialization of a template as a friend (so that BlobPtr<int> is a friend of Blob<int> but BlobPtr<long> is not), then you first need to tell the compiler that BlobPtr is a template in the first place - that's what you need forward declaration for.

Force instantiation of friend functions

Assume we have a template class with friend function:
template<class T>
class A {
friend A operator+ (int, const A&);
};
This function is implemented somewhere below:
template<class T>
A<T> operator+ (int i, const A<T>& a) {
...
}
And also there is force instantiation of class template further below:
template class A<int>;
Does this imply that operator+(int, A<int>) will be compiled? Or do I have to force instantiate it separately to achieve that?
Template parameters aren't automatically forwarded to friend declarations. You need to specify a template parameter for the function as well:
template<class T>
class A {
template<class U>
friend A<U> operator+ (int, const A<U>&);
};
Implementation is almost correct, should be
template<class T>
A<T> operator+ (int i, const A<T>& a) {
// ^^^
// ...
}

Non-member operator overloading of inner class templates

I prefer to write definitions for class and function templates in a separate file which is automatically included after the "public" header. However, I've come to an interesting case where it looks like I can't do that.
template <typename T>
class Outer
{
public:
template <typename U>
class Inner
{
friend bool operator ==(const Inner& lhs, const Inner& rhs);
};
};
using Type = Outer<int>::Inner<short>;
int main()
{
Type a;
Type b;
a == b;
}
Is it possible to write definition of operator== separately that will work for any T and U?
For a particular specialization, yes:
template <typename T>
class Outer
{
public:
template <typename U>
class Inner
{
int x = 42;
friend bool operator ==(const Inner& lhs, const Inner& rhs);
};
};
using Type = Outer<int>::Inner<short>;
bool operator ==(const Type& lhs, const Type& rhs) {
return lhs.x == rhs.x;
}
int main()
{
Type a;
Type b;
a == b;
}
In your example, each specialization of the template befriends a non-template function that takes that particular specialization as parameters. You could define this function in-class (and then it will be stamped out every time the template is instantiated), or you could define it out-of-class - but then you would have to define one for every specialization you ever use.
As Igor Tandetnik points out, your example declares a non-template friend function, which you'll have to overload for each template instantiation, which is one reason friend functions are allowed to be defined inline (so they can be generated by the template without having to be templates themselves).
If you want to define the friend function as a template, here is the closest I was able to come up with:
template <typename T>
struct Outer {
template <typename U>
struct Inner;
};
template<typename T, typename U>
bool operator==( typename Outer<T>::template Inner<U> const &, typename Outer<T>::template Inner<U> const & );
template <typename T>
template <typename U>
struct Outer<T>::Inner {
friend bool operator==<T,U>(Inner const &, Inner const &);
};
template<typename T, typename U>
bool operator==( typename Outer<T>::template Inner<U> const &, typename Outer<T>::template Inner<U> const & ) {
return true;
}
// I switched this out, because my gcc-4.6 doesn't
// understand "using" aliases like this yet:
typedef Outer<int>::Inner<short> Type;
int main() {
Type a;
Type b;
operator==<int,short>( a, b );
}
Unfortunately, you'll notice the call site of this operator function is very awkward: operator==<int,short>( a, b ). I believe defining a function template on a nested class template like this disables (or at least interferes with) argument deduction, so you have to specify the template parameters explicitly (which means calling it as a function rather than in operator form). This is why the inline friend definition is so convenient. If you really want to define your operator=='s code separately, I'd recommend defining the friend inline to call another function template (with the proper template arguments), which you can then define out-of-line as a free function.

Overload output stream operator of a template class outside of the template

I want to overload the output stream operator << outside the template class definition.
Implementing it inside the template class is ok:
template
<typename T,int _MaxSize=10,template <class C> class Policy=NoCheck,typename Container=std::vector<T>>
class MyContainer : public Policy<T>
{
public:
MyContainer():p(_MaxSize){};
std::ostream& operator<<(MyContainer<T,_MaxSize,Policy,Container>& obj){ };
private:
Container p;
};
But when I tried to do it outside the template class:
template
<typename T,int _MaxSize=10,template <class C> class Policy=NoCheck,typename Container=std::vector<T>>
class MyContainer : public Policy<T>
{
public:
MyContainer():p(_MaxSize){};
friend std::ostream& operator<<(std::ostream& out,MyContainer<T,_MaxSize,Policy,Container> obj);
private:
Container p;
};
template
<typename T,int _MaxSize,template <class C> class Policy,typename Container>
std::ostream& operator<<(std::ostream& out,MyContainer<T,_MaxSize,Policy,Container> obj)
{
};
Compiler complains:
warning: friend declaration ‘std::ostream& operator<<(std::ostream&, MyContainer<T, _MaxSize, Policy, Container>)’ declares a non-template function [-Wnon-template-friend]
tempstruct.cc:39:97: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)
Can anybody give a simple example on how can the output stream operator << defined outside a template class?
In the related posts that I found here everyone do it inside the template class.
Can anybody give a simple example on how can the output stream operator << defined outside a template class?
No, because it's not simple. I can give a complicated example:
// Declare the class template, because we need it to declare the operator
template <typename,int,template <class C> class,typename> class MyContainer;
// Declare the operator, because (as the error says) templates must be declared
// in the namespace before you can declare them friends. At this point, we can't
// define the operator, since the class template is incomplete.
template
<typename T,int _MaxSize,template <class C> class Policy,typename Container>
std::ostream& operator<<(std::ostream&,MyContainer<T,_MaxSize,Policy,Container>);
// Define the class template
template
<typename T,int _MaxSize=10,template <class C> class Policy=NoCheck,typename Container=std::vector<T>>
class MyContainer : public Policy<T>
{
public:
MyContainer():p(_MaxSize){};
// Include <> to indicate that this is the template
friend std::ostream& operator<< <>(std::ostream& out,MyContainer<T,_MaxSize,Policy,Container> obj);
private:
Container p;
};
// Finally define the operator
template
<typename T,int _MaxSize,template <class C> class Policy,typename Container>
std::ostream& operator<<(std::ostream& out,MyContainer<T,_MaxSize,Policy,Container> obj)
{
// print some stuff
};
In the related posts that I found here everyone do it inside the template class.
I'd do that; it would be much simpler. Or, better still, I'd implement output in terms of the public interface, assuming it gives sufficient access to the container's contents. Then you wouldn't need the friend declaration, so wouldn't need the forward declarations either.