c++ - 为什么在 gcc/libstdc++ 的 __enable_shared_from_this_helper 中没有模板参数

标签 c++ shared-ptr libstdc++

我正在阅读 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/

相关文章:

C++ Visual Studio, 'vc_attributes::YesNoMaybe' : 'enum' type redefinition error

c++ - 如何在不取消定义类型的情况下为 C++ 中的类型编写 getter?

macos - 如何在 OS X 上构建 fat gcc46 libstdc++?

c++ - std::move weak_ptr::lock 的返回值弄乱了 shared_ptr 的引用计数?

c++ - 为什么 valgrind 报告 libstdc++ 的 std::locale 错误?

c++ - 尝试理解 libstdc++ 对 std::multiset 的实现

c++ - 如何将 std::chrono 包装在 C++ 迭代器类型中

c++ - FOR_EACH 宏在调用宏中有两个或多个参数

c++ - 从 libav 收集解码的音频作为 double

带有宏的类中的 C++ 自动 shared_ptr 类型