在g ++上使用不完整类型无效

lei*_*iiv 8 c++ g++ class

我有两个相互依赖的类:

class Foo; //forward declaration

template <typename T>
class Bar {
  public:
    Foo* foo_ptr;
    void DoSomething() {
      foo_ptr->DoSomething();
    }
};

class Foo {
  public:
    Bar<Foo>* bar_ptr;
    void DoSomething() {
      bar_ptr->DoSomething();
    }
};
Run Code Online (Sandbox Code Playgroud)

当我用g ++编译它时,它给出了"无效使用不完整类型"的错误,但它在MSVC 10中编译得很好.是否有可能在将声明和定义保存在一个头文件中时解决这个问题?(没有cpp文件)如果标准中不允许这样,那么这个MSVC"bug"或"feature"是哪一个?

R S*_*hko 8

是的,只需将方法定义移出类定义:

class Foo; //forward declaration

template <typename T>
class Bar {
  public:
    Foo* foo_ptr;
    void DoSomething();
};

class Foo {
  public:
    Bar<Foo>* bar_ptr;
    void DoSomething() {
      bar_ptr->DoSomething();
    }
};

// Don't forget to make the function inline or you'll end up
// with multiple definitions
template <typename T>
inline void Bar<T>::DoSomething() {
  foo_ptr->DoSomething();
}
Run Code Online (Sandbox Code Playgroud)