2014-12-03 37 views
2

我正在读取enable_shared_from_this的stl代码,它位于gcc-4.9.2 \ libstdC++ - v3 \ include \ bits \ shared_ptr.h中。然后我看到这一点:为什么在__enable_shared_from_this_helper中没有模板参数在gcc/libstdC++

template<typename _Tp1> 
friend void 
__enable_shared_from_this_helper(const __shared_count<>& __pn, 
       const enable_shared_from_this* __pe, 
       const _Tp1* __px) noexcept 
{ 
    if (__pe != 0) 
    __pe->_M_weak_assign(const_cast<_Tp1*>(__px), __pn); 
} 

我的问题是,为什么没有为常量模板参数enable_shared_from_this * __pe?当shared_ptr构造函数使用指向A类的指针调用__enable_shared_from_this_helper时,它如何工作,其中A是从enable_shared_from_this派生的?

回答

3

这是在enable_shared_from_this定义的内部定义的。在类模板的定义中,模板名称也是注入的类名称,可以在没有限定的情况下使用来引用正在实例化的任何特定类型。

3

这就是所谓的注入类名。所述C++标准允许此例如在14.6.1:

像正常(非模板)类,类模板具有 注入类名(第9节)。注入的类名可以使用 作为模板名称或类型名称。当它与 模板参数列表一起使用时,作为模板参数的模板参数或作为朋友类模板声明的详细类型 说明符中的最终标识符,它指的是 类模板本身。 否则,它相当于 模板名称,后面跟着<>中包含的类别 模板的模板参数。

如果你看一下shared_ptr_base.h的源代码,你可以看到所需模板参数,因为它是类外

00730 // Friend of __enable_shared_from_this. 
00731 template<_Lock_policy _Lp, typename _Tp1, typename _Tp2> 
00732  void 
00733  __enable_shared_from_this_helper(const __shared_count<_Lp>&, 
00734      const __enable_shared_from_this<_Tp1, 
00735      _Lp>*, const _Tp2*); 

shared_ptr.h,定义为类内

00473 template<typename _Tp> 
00474  class enable_shared_from_this 
00475  { 

... 

00502  template<typename _Tp1> 
00503  friend void 
00504  __enable_shared_from_this_helper(const __shared_count<>& __pn, 
00505      const enable_shared_from_this* __pe, 
00506      const _Tp1* __px) 
00507  { 
00508  if (__pe != 0) 
00509   __pe->_M_weak_assign(const_cast<_Tp1*>(__px), __pn); 
00510  } 
相关问题