如何基于特定派生类调用方法
How to call a method based on a specific derived class
我试图了解弱指针成员(使用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的以下帖子中得到了很好的解释:
为什么不专门化函数模板?
相关文章:
- 在c++中多次调用方法
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 接收字符串并使用它来调用方法C++
- 使用 gmock c++ 在真实对象上调用方法
- 不带预处理器的调用方法/文件的文件名/行号
- JNI从Android调用C++方法
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何使用接口指针调用方法,该指针是其具体类的一部分,而不是接口的一部分
- 从内部类中的方法从包含类调用方法
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 为什么派生类的实例从基类调用方法?
- 实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?
- C++当您取消引用指向类对象的指针,然后将其作为引用返回时,是否可以对此引用调用方法
- 通过模板函数对未知类型调用方法
- 从基于迭代器的for循环转换后,如何在map::find()中调用方法
- 创建一个C++DLL以从C#DLL调用方法
- 如何从qt中的类中调用方法
- 如何在不迭代的情况下对数组中的每个元素调用方法
- C++11 - 获取编译时的所有类变量,并在没有 Boost 的情况下为它们调用方法
- C ++:如何在不创建对象的情况下在主函数中调用方法