How to Declare a Templated Struct/Class as a Friend

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?

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 template function a friend of a templated nested class?

I have tried declaring it out of class by making inner have a template <typename V, typename W> friend inner<V> get(outer<W>&);

You need to declare the template function before the friend declaration, to tell the compiler that get is a template. E.g.

// definition of outer
template <typename T>
struct outer {

// forward declaration of inner
template <typename U>
class inner;
};

// declaration of get
template <typename V, typename W>
typename outer<W>::template inner<V> get(outer<W>&);

// definition of inner
template <typename T>
template <typename U>
class outer<T>::inner {
inner() {}
public:
// friend declaration for get<U, T>
friend inner<U> get<U>(outer<T>&);
};

// definition of get
template <typename V, typename W>
typename outer<W>::template inner<V> get(outer<W>&) {
return {};
}

LIVE

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.

Declaring a class template as a friend of a class template in C++

The following code builds fine on gcc. I added a definition of B<T>::add(T), as it was missing. It's very possible that the absence caused your link - not compilation! - error.

template<typename T>
class B;

template <typename T>
class A {
private:
T content;

friend B<T>;
};

template <typename T>
class B {
public:
void add(T t) { A<T> a; a.content = t; }

private:
A<T>* ptr;
};

int main() {
A<int> a;
B<int> b;
b.add(3);
}


Related Topics



Leave a reply



Submit