模板好友函数重载

template friend function overloading

本文关键字:重载 函数 好友      更新时间:2023-10-16

过去两天我正在阅读std::enable_shared_from_this(g++版本)源代码。有两个问题让我感到困惑。
让我先展示一下简短的源代码。

template<typename _Tp>
class enable_shared_from_this {
...
private:
template<typename _Tp1>
friend void
__enable_shared_from_this_helper(const __shared_count<>& __pn,
const enable_shared_from_this* __pe,
const _Tp1* __px) noexcept {
}
};
template<typename _Tp1, typename _Tp2>
void
__enable_shared_from_this_helper(const __shared_count<>&,
const enable_shared_from_this<_Tp1>*,
const _Tp2*) noexcept;

问题:
1。注意行const enable_shared_from_this* __pe,没有标记'<>'在enable_shared_from_this之后,这在这里是否意味着enable_shared_from_this<__Tp1>
2。这里有两个重载函数模板__enable_shared_from_this_helper,我的测试表明,class enable_shared_from_this中定义的版本总是会被调用,为什么?

谢谢你们,如果有任何努力,我将不胜感激。

对于1.:否,这意味着<_Tp>在这里是隐式的,而不是来自附加模板参数的<_Tp1>。如果在类的定义(或成员方法定义的主体)中省略了类名的模板参数,并且需要类型,则隐含了类本身的参数。

对于2.:这与第一个相同,只是用_Tp1代替_Tp,用_Tp2代替_Tp1