c++ - 具有前向声明类的模板函数

标签 c++ templates

菜鸟问题在这里。我有一个循环依赖类,所以我转发声明它。现在,我打算用这个尝试一个模板。

//在C.h中

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

//在 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)
       }
    }

这无法在指定的行编译,说明 C 类没有函数“getMap()”。这可以修复吗?如果是,怎么办?

最佳答案

changeProperty 的定义移出类(因此它不是 inline)并将其放置在 class C 定义之后的某处被看见了。

所以预处理后的结果最终会是这样的:

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)
   }

关于c++ - 具有前向声明类的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16670193/

相关文章:

c++ - 控制台获取按键 w/o windows 消息 c++

c++ - 模块最终允许标准库实现中的可读名称吗?

c++ - 使用模板参数添加数据

C++如何在删除上一行后使用同一行打印文本?

c++ - CUDA 图像不显示输出

c++ - 使用 const char * 时如何将记录器与模板一起使用?

iphone - 自定义 XCode 模板?

c++ - 模板参数

c++ - 编译时模板值推导

c++ - 对于在 C++ 中找不到异常,您会怎么想?