remove_cvref_t:你也读得懂的源码

template <class _Ty>
using remove_cvref_t = _Remove_cvref_t<_Ty>;

源码是msvc的,同时去掉了一些宏……那些宏很影响主要的逻辑吗?

上面是using,让我们继续跳转

using _Remove_cvref_t = remove_cv_t<remove_reference_t<_Ty>>;

这里出现了两个我们感兴趣的玩意,直接一步到位:

template <class _Ty>
struct remove_cv { // remove top-level const and volatile qualifiers
    using type = _Ty;

    template <template <class> class _Fn>
    using _Apply = _Fn<_Ty>; // apply cv-qualifiers from the class template argument to _Fn<_Ty>
};

template <class _Ty>
struct remove_cv<const _Ty> {
    using type = _Ty;

    template <template <class> class _Fn>
    using _Apply = const _Fn<_Ty>;
};

template <class _Ty>
struct remove_cv<volatile _Ty> {
    using type = _Ty;

    template <template <class> class _Fn>
    using _Apply = volatile _Fn<_Ty>;
};

template <class _Ty>
struct remove_cv<const volatile _Ty> {
    using type = _Ty;

    template <template <class> class _Fn>
    using _Apply = const volatile _Fn<_Ty>;
};

这里是几个模板特化,如果匹配到特化的话(以const为例),这里的::type会去除_Ty的const

不信可以做个试验:

	using T = std::remove_cvref_t<const int>;
	if constexpr (std::is_same_v<T, int>) {
		std::cout << "Yeah" << "\n";
	}
	else if constexpr (std::is_same_v<T, const int>) {
		std::cout << "wc" << "\n";
	}

remove_reference_t也是一样的道理:

template <class _Ty>
struct remove_reference {
    using type                 = _Ty;
    using _Const_thru_ref_type = const _Ty;
};

template <class _Ty>
struct remove_reference<_Ty&> {
    using type                 = _Ty;
    using _Const_thru_ref_type = const _Ty&;
};

template <class _Ty>
struct remove_reference<_Ty&&> {
    using type                 = _Ty;
    using _Const_thru_ref_type = const _Ty&&;
};

去除引用/右值引用

所以stl的源码也并不全是很复杂的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值