Mutual return types of member functions (C ++)

Is it possible that in C ++ there are two classes, call them A and B , so that A has a member function f that returns an object of class B and B has a member function g that returns an object of class A ?

(The text below is just to show that I "did my homework.")

The problem is how to write the signatures of these functions when one in the first defined class will have an incomplete return type. Advanced declarations do not help here, because objects are returned by value.

Yes, I know all the workarounds (common global functions of a friend returned by a pointer ...), but I would just like to find out if the interface described above can be implemented in C ++. For example, suppose I try to overload operator () in class A to return B , and in class B to return A Since I overload operators, I have to return by value (well, if I do not want to allocate hell dynamically :), and () should be overloaded as a member function, so I can not use global friends.

+4
source share
2 answers

Yes, make class A function definitions after you declare class B

 class B; class A { B f(); }; class B { A g() { A a; return a; } }; BA::f(){ B b; return b; } 
+7
source

Another possible way to break the dependency loop is to use a member function of the template, for example:

 struct A { template<typename T> T f() { return T(); } }; struct B { A g() { return A(); } }; int main() { A a; B b = af<B>(); A a1 = bg(); return 0; } 

It will work for operator (), although the call syntax will be pretty ugly: a.operator()<B>()

0
source

All Articles