Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you mark a struct template as friend?

I have code like this:

template <typename T, typename U> struct MyStruct {
    T aType;
    U anotherType;
};

class IWantToBeFriendsWithMyStruct
{
    friend struct MyStruct; //what is the correct syntax here ?
};

What is the correct syntax to give friendship to the template ?

like image 538
David Avatar asked Oct 15 '08 19:10

David


People also ask

How do I declare a friend template class in C++?

class B{ template<class V> friend int j(); } template<class S> g(); template<class T> class A { friend int e(); friend int f(T); friend int g<T>(); template<class U> friend int h(); }; Function e() has a one-to-many relationship with class A . Function e() is a friend to all instantiations of class A .

Can we declare a template function as the friend of the class?

A template friend declaration can name a member of a class template A, which can be either a member function or a member type (the type must use elaborated-type-specifier).

Can structs be templated?

The entities of variable, function, struct, and class can have templates.


2 Answers

class IWantToBeFriendsWithMyStruct
{
    template <typename T, typename U>
    friend struct MyStruct;
};

Works in VS2008, and allows MyStruct to access the class.

like image 177
Rob Walker Avatar answered Sep 30 '22 19:09

Rob Walker


According to this site, the correct syntax would be

class IWantToBeFriendsWithMyStruct
{
    template <typename T, typename U> friend struct MyStruct; 
}
like image 38
Lev Avatar answered Sep 30 '22 20:09

Lev