【问题标题】:Which members are inherited from the template parameter哪些成员继承自模板参数
【发布时间】:2016-11-11 18:14:04
【问题描述】:

如果我们有一个像

这样的类模板
template<class Type>
class Field {
....
}; 

现在,如果我将 Field 类的对象声明为

Field <vector> velocityField;

那么哪些成员函数从vector继承到我的velocityField

【问题讨论】:

  • 什么是vector?你是说std::vector
  • 没有继承任何东西。如果你想继承,你必须写 template&lt;class Type&gt; class Field : public Type{}; 之类的东西,然后应用常规继承规则。

标签: c++ inheritance class-template


【解决方案1】:

当编译器找到具体类型的声明时,模板参数允许编译器执行通用模板参数本身的替换。你没有继承任何东西。

如果您在Field 类中的某处使用Type,则会相应地执行替换,并且编译器只会查找引用的方法。

template<class Type>
class Field {
  void Foo()
  {
    Type instanceOfType;
    instanceOfType.clear();
  }
  void NeverCalledMethod()
  {
     Bar(); //bar doesn't exist
  }
}; 

Field<vector> aField; // here the type Field<vector> is instantiated for the first time.
aField.Foo(); // only here the template class Foo() method is included by the compiler.

在某些情况下(例如Bar() 的主体具有有效的语法),编译不会受到其主体中的错误的影响,如果Bar() 从未被调用。 因为Bar() 它从未被调用过,编译器可以解析它但不会尝试实际编译它,所以上面的代码不会产生任何编译器错误。

【讨论】:

  • 回复。最后一句,有一些限制。对于初学者,它不能包含语法错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-15
  • 1970-01-01
  • 2012-03-13
  • 2012-10-26
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
相关资源
最近更新 更多