我正在阅读 enable_shared_from_this 的 STL 代码,它在 gcc-4.9.2\libstdc++-v3\include\bits\shared_ptr.h 中。然后我看到了这个:
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);
}
我的问题是,为什么 const enable_shared_from_this* __pe 没有模板参数?当 shared_ptr 构造函数使用指向类 A 的指针调用 __enable_shared_from_this_helper 时,它是如何工作的,其中 A 派生自 enable_shared_from_this?
最佳答案
这被称为注入(inject)类名。 C++ 标准 允许这样做,例如在 14.6.1 中:
Like normal (non-template) classes, class templates have an injected-class-name (Clause 9). The injected- class-name can be used as a template-name or a type-name. When it is used with a template-argument-list, as a template-argument for a template template-parameter, or as the final identifier in the elaborated-type- specifier of a friend class template declaration, it refers to the class template itself. Otherwise, it is equivalent to the template-name followed by the template-parameters of the class template enclosed in <>.
如果您查看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 }
关于c++ - 为什么在 gcc/libstdc++ 的 __enable_shared_from_this_helper 中没有模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27271941/