且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么C ++模板让我绕开不完整的类型(转发声明)?

更新时间:2022-06-23 05:11:43

第一个需要定义 container ,因为您正在进行复制操作。如果你在 container 的定义后定义 iter 的构造函数,那么你就没关系了。所以:

The first requires a definition of container since you are doing a copy operation. If you define the constructor of iter after container's definition you'd be okay. So:

struct container;
struct iter {
  container &c;
  int *p;
  iter(container &c);
};

struct container {
  int x;
  int &value() { return x; }
  iter begin() { return iter(*this); }
};

iter::iter(container &c) : c(c), p(&c.value()) {}

int main() {
  container c;
  c.begin();
  return 0;
}

第二个示例工作,因为没有类,除非你实际上 main 函数。到那时,所有类型都被定义。尝试移动main之后的任何 iter 容器模板定义,您会遇到错误。

The second example works because there is no class until you actually instantiate one in your main function. By that time all types are defined. Try moving any of the iter or container templates definition after main and you'll hit an error.

第三个例子是 int 的专用化,因此出现。这应该编译,因为 iter 的模板参数不使用。你有专业化语法一点。但是,没有合适的构造函数,所以你只会得到 x 的垃圾。此外,迭代器通过指针很好地建模。传递这个的值将没有太多帮助。迭代器通常是序列所需,而不是单个对象。

The third example is a specialization for int or so it appears. This should compile because the template parameter for iter is not used. You've got the specialization syntax a bit off. However, there is no proper constructor so you'll only get garbage for x. Moreover, iterators are modeled well by pointers. Passing this's value will not be of much help. Iterators are typically required for a sequence and not an individual object. Though, there is nothing that can stop you from building one.

然后你不需要; $ c>功能体。

And you don't need a ; after a function body.