且构网

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

为什么当一个模板类从另一个模板类继承时,需要重新指定typedef并限定函数调用?

更新时间:2023-02-11 19:20:46

根本原因是类可以专门化:

The fundamental reason is that classes can be specialized:

template<class T>
struct A {};

template<class T>
struct B : A<T> {
  typedef typename A<T>::referent target;
  void niceName() {A<T>::uglyName();}
};

template<class T>
struct A<T*> {
  typedef T referent;
  void uglyName();
};

B<int*>::target i;  // OK: int

当然,相反的情况(主模板定义了有用的东西,而我们只是 fear 担心专业化可能会更改或删除它们)更常见,这使规则看起来是任意的.

Of course, the reverse case (where the primary template defines useful things, and we simply fear that a specialization might change or remove them) is more common, which makes the rule seem arbitrary.