How to Mark a Struct Template as Friend

How do you mark a struct template as friend?

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

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

How to declare a templated struct/class as a friend?

template<typename> friend class foo

this will however make all templates friends to each other.
But I think this is what you want?

Template class friendship

There's no point indeed to make a class a friend to itself, except if it is a template class. For example the following code makes sense:

template <class T>
class A
{
template<class U>
friend class A;
}

An STL example is the std::_Ptr_base which is the base class for std::shared_ptr and std::weak_ptr.

Class template with template class friend, what's really going on here?

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.

Making a class or struct to be friend of all template instantiated class?

Here's a workaround for this odd issue...

Create a struct with a nested struct that inherits the inner structs :

template <class... Types>
struct BaseInherit {
struct Inner : public Types::Inner... {};
};

Then, inherit from BaseInherit's nested inner in Base :

template <class... Types>
class Base : public BaseInherit <Types...>::Inner {};

This is what I had to do for GCC (6.3.1).

Edit: Forgot to say that you would then add BaseInherit as the friend struct, and not Base. Example :

class S1 {

template <class... Types>
friend struct BaseInherit;

struct Inner { int member1, member2; };

};

Edit : How the workaround was found - I was trying to figure out the order in which the compiler would deduce variadic templates when inheriting. Since it complained when they were directly inherited, I thought that it may work in the scope of the class. Of course, we can't inherit from its own nested struct, so we put it in another struct / public class's nested struct.



Related Topics



Leave a reply



Submit