dev_nut
dev_nut

Reputation: 2542

Template function with a forward declared class

Noob question here. I have a class with a circular dependency so I forward declared it. Now, I'm planning to try out a template with this.

//in C.h

class C {
public:
  virtual void getMap();
}

// in A.h

    class C;
    class A {
    public:
       virtual void foo(C *c);

    template <class T>     
       void changeProperty(C *c, string& s) {
          void* obj = c->getMap()->at(s); // does not compile 
          // (did not include the rest for brevity)
       }
    }

This fails to compile at the line specified stating that Class C doesn't have a function 'getMap()'. Can this be fixed? If so, how?

Upvotes: 1

Views: 87

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171433

Move the definition of changeProperty out of the class (so it's not inline) and place it somewhere after the definition of class C has been seen.

So the preprocessed result will end up as something like:

class C;
class A {
public:
   virtual void foo(C *c);

template <class T>     
   void changeProperty(C *c, string& s);
}

// ...

class C {
public:
  virtual void getMap();
}

// ...

template <class T>     
   void A::changeProperty(C *c, string& s)
   {
      void* obj = c->getMap()->at(s); // compiles
      // (did not include the rest for brevity)
   }

Upvotes: 3

Related Questions