如何基于特定派生类调用方法

How to call a method based on a specific derived class

本文关键字:调用 方法 派生 何基于      更新时间:2023-10-16

我试图了解弱指针成员(使用visual studio 2013 C++编译器)

mutable weak_ptr<_Ty> _Wptr

来自模板类的enable_shared_from_this是在从其派生的对象中创建std::shared_ptr<_Ty>时初始化的。为此,我使用模板函数std::make_share<_Ty> 从创建std::shared_ptr<_Ty>的简单代码中跟踪代码

我发现_Wptr的初始化是在编译器调用基类_Ref_count_del_alloc中的方法_Enable_shared时进行的。

现在为此定义了2个模板方法。当_Ty类从enable_shared_from_this派生时,定义了一种方法。这是一种方法:

template<class _Ty>
inline void _Enable_shared(_Ty *_Ptr, _Ref_count_base *_Refptr,
    typename _Ty::_EStype * = 0)
{   // reset internal weak pointer
if (_Ptr)
    _Do_enable(_Ptr,
        (enable_shared_from_this<typename _Ty::_EStype>*)_Ptr, _Refptr);
}

第二种方法是在_Ty不是从enable_shared_from_this派生的时定义的。这是一种方法:

inline void _Enable_shared(const volatile void *, const volatile void *)
{   
    // not derived from enable_shared_from_this; do nothing
}

我的问题是C++编译器如何解决使用哪种方法?此外,我还希望这两个方法都在编译时实例化,如果类不是从enable_shared_from_this派生的,则会出现编译错误。然而,编译器似乎只选择了一个要实例化的方法和适当的方法。

在深入研究代码后,我发现了解如何做到这一点的关键是通过Kerry SB所指出的函数模板专门化。由于_EStype仅在enable_shared_from_this基模板类中定义,因此编译器能够根据参数中不太格式错误的调用在_Enable_shared函数模板之间进行选择。

这在Herb Sutter的以下帖子中得到了很好的解释:

为什么不专门化函数模板?