Template function friend template class template

I have the following simplified code:

template <class T> class A { public: template <class U> static U foo(T* p) { p; return U(); } }; class B { /*template <class T> template <class U> friend U A<T>::foo<U>(T*);*/ friend B A<B>::foo<B>(B*); B() {} public: }; ... A<B>::foo<B>(nullptr); 

And it works very well. But what I failed to do is commented out:

 /*template <class T> template <class U> friend U A<T>::foo<U>(T*);*/ 

I don't know what syntax I have to use to make it work. Therefore, I need to generalize my declaration of friends to all possible types. I tried several syntax options but did not succeed. Can someone tell me what should I write instead of my commented code for it to work? Thanks!

+4
source share
2 answers

What you are looking for is

 template <class T> template <class U> friend U A<T>::foo(T*); 

The following works on IdeOne.com

 #include <iostream> template <class T> class A { public: template <class U> static U foo(T* p) { p; return U(); } }; class B { template <class T> template <class U> friend U A<T>::foo(T*); B() {} public: void hello() const { std::cout << "I'm a B!" << std::endl; } }; int main(int, char*[]) { A<B>::foo<B>(NULL).hello(); } 
+2
source

I agree with the comments, friends and templates, just don't mix, at least not in any way consistent with many compilers. The standard probably defines exactly what should work, although it probably won't help you. Sad, but true.

A friend is often not a good idea, so it’s better to think about how to write code without friendship, or use the β€œbad friend-man” public method with a comment indicating that this is not for general use.

0
source

Source: https://habr.com/ru/post/1402097/


All Articles