Martin Heralecký
Martin Heralecký

Reputation: 5779

Two template classes with methods calling each other

Two template classes have two methods each which call the other class's method:

// Foo.h
template<typename T>
class Foo {
public:
    static void call_bar() {
        Bar<int>::method();
    }

    static void method() {
        // some code
    }
};

// Bar.h
template<typename T>
class Bar {
public:
    static void call_foo() {
        Foo<int>::method();
    }

    static void method() {
        // some code
    }
};

How can I get this to work? Simply adding #include "Bar.h" to Foo.h (or vice versa) doesn't work because each class needs the other one.

EDIT: I also tried forward declarations, but it still fails at linking stage:

// Bar.h
template <typename T>
class Foo {
public:
    static void method();
};

// Foo.h
template <typename T>
class Bar {
public:
    static void method();
};

Upvotes: 2

Views: 543

Answers (1)

R Sahu
R Sahu

Reputation: 206607

When you have two class templates that are dependent on each other, using two .h files does not make sense. In order to be able to use Foo, you need both Foo.h and Bar.h. In order to be able to use Bar, you also need both Foo.h and Bar.h. It's best to put them in one .h file.

  1. Define the classes.
  2. Implement the member functions at the end.

FooBar.h:

template<typename T>
class Foo {
   public:
      static void call_bar();

      static void method() {
         // some code
      }
};

template<typename T>
class Bar {
   public:
      static void call_foo();

      static void method() {
         // some code
      }
};

template<typename T>
void Foo<T>::call_bar() {
   Bar<int>::method();
}

template<typename T>
void Bar<T>::call_foo() {
   Foo<int>::method();
}

Upvotes: 5

Related Questions