Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'd like to do the following:

template <typename T> struct foo {     template <typename S>     friend struct foo<S>;  private:     // ... }; 

but my compiler (VC8) chokes on it:

error C3857: 'foo<T>': multiple template parameter lists are not allowed 

I'd like to have all possible instantiations of template struct foo friends of foo<T> for all T.

How do I make this work ?

EDIT: This

template <typename T> struct foo {     template <typename>     friend struct foo;  private:     // ... }; 

seems to compile, but is it correct ? Friends and templates have very unnatural syntax.

like image 870
Alexandre C. Avatar asked Jul 20 '10 17:07

Alexandre C.


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(); };

Can structs be templated?

You can template a struct as well as a class. However you can't template a typedef.

Can a class be friend in C++?

Friend Keyword in C++ But, to declare any class as a friend class, you do it with the friend keyword. You can use the friend keyword to any class to declare it as a friend class. This keyword enables any class to access private and protected members of other classes and functions.

How do you declare a friend function in C++?

A friend function is declared inside the class with a friend keyword preceding as shown below. class className{ …… friend returnType functionName(arg list); }; As shown above, the friend function is declared inside the class whose private and protected data members are to be accessed.


1 Answers

template<typename> friend class foo 

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

like image 122
Anycorn Avatar answered Sep 20 '22 17:09

Anycorn