0

While thinking about my current programming project, I bumped into the following problem:
I have 2 template classes, where each one should be able to invoke a call on the other one, like outlined by the code below.

Question: Is there a way to keep this code in seperate header files (one for A and one for B)?

template <typename T>
class B;


template <typename T>
class A {
public:
    void foo() {
        m_b->bar();
    }

    void bar() {
        // ...
    }
private:
    B<T> *m_b;
};


template <typename T>
class B {
public:
    void foo() {
        m_a->bar();
    }

    void bar() {
        // ...
    }
private:
    A<T> *m_a;
};

EDIT: I just noticed, that the real question is:
If I have the files A.h and B.h, is there a way to call A::foo() from another file that just includes A.h?

1 Answer 1

0
  1. using forward declaration.
  2. move the implementation of the functions outside of the declaration of the template class.
  3. in the cpp file (the implementation), you still need to include both headers though.
3
  • Thanks for the answer. It works using forward declaration in both files. I think, I forgot to clarify this: If I have A.h and B.h, is there a way to call A::foo() from another file that does not include B.h? Sep 19, 2013 at 23:51
  • @MalteLangkabel I don't see how. It invokes member B::bar() which must be known in the translation unit. You could get a little more abstract and make one of them a template-template parameter to the other, but you still need both to be known by the translation unit to do what you're describing.
    – WhozCraig
    Sep 19, 2013 at 23:59
  • @WhozCraig: Seems like you are right. Otherwise I could indirectly call B::bar() without ever including B.h. Sep 20, 2013 at 0:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.