Reputation: 380
Given two template classes, each with member functions which refer to member functions in the others class, how can this be done? If at all. By using forward declaration to allow the cyclic dependency, means the definition isn't available for the referenced member function. So an error regarding implicit instantiation of an undefined type occurs. The definitions of the member functions can't be pushed to the cpp file, with the full class definitions included instead of forward declarations, as it must exist in the header to allow compiler instantiation upon usage/call.
template<typename T>
class A {
void foo(B &b) { b.bar(); };
void bar() {};
}
template<typename T>
class B {
void foo(A &a) { a.bar(); };
void bar() {};
}
Now I know the first response will be "change your code", but I'm experimenting with something, and this is the only way I can see to make it work. So I'm interested in whether the above is at all possible in C++. Many thanks in advance!
Upvotes: 1
Views: 43
Reputation: 477338
Declare one template before defining the other:
template <typename> class B;
template <typename T> class A {
inline void foo(B<T> &b);
inline void bar();
};
template <typename T> class B {
void foo(A<T> &a) { a.bar(); }
void bar() {}
};
template <typename T> void A<T>::foo(B<T> &b) { b.bar(); }
template <typename T> void A<T>::bar() {}
Upvotes: 5