views:

84

answers:

1

Hi!

usually, if my #include chain gets circular, I solve it by replacing one of the #includes by a forward declaration and then move all the function implementations that depend on this type into the cpp file, where I #include the header instead.

But - in some situations it's bad to put function implementation into the cpp file - especially when dealing with templates or for inline functions.

Therefore - Are there other ways to deal with circular #include chains rather than using forward declarations?

thanks!

+7  A: 

You should limit such circular dependencies because they make code difficult to understand and hard to work with.

That said, sometimes such dependencies are necessary. In those cases, you can declare all of the entities in a single header file, then after all of the declarations provided definitions for any function templates and inline functions. For example:

#ifndef MY_AWESOME_INCLUDE_GUARD
#define MY_AWESOME_INCLUDE_GUARD

template <typename> struct B;

template <typename T>
struct A
{
    template <typename U>
    void f(B<U>);
};

template <typename T>
struct B
{
    template <typename U>
    void f(A<U>);
};

template <typename T>
template <typename U>
void A<T>::f(B<U>) { }

template <typename T>
template <typename U>
void B<T>::f(A<U>) { }

#endif
James McNellis