模板类 的完美转发

通过一个小List,实现模拟迭代器,之前很少写过模板的东西,起初我认为和普通函数一样,但实际中遇到了一些问题

如下函数

错误的万能引用

template <typename T>
class A{
    func(T &&value);
}

实际上 由于T是模板类的关系,这样写在func中 T不能起到推导作用,func的参数只是一个普通的右值引用参数

在模板类中实现万能的引用函数。即完美转发,需要再使用一个新的模板类型

template<typename T>
class List{
    //...

    template <typename U>
        void insert_front(U &&value) {
        //...   
        ListItem <T>*temp = new ListItem<T>(std::forward<U>(value));
        //...
        }
    //...
     }

其中类ListItem 拥有接受右值和左值的构造 insert_front函数可以成功实现完美转发

但事实上,这样仍然存在一个问题,如此设计出来的参数U和T实际上并不相关的。违背设计初衷。
如果List被初始化为一个int容器,那么实际上insert_front仍然可以传入其他类型参数。

可以通过如下方法

 static_assert(std::is_same<std::decay_t<U>,std::decay_t<T>>::value, 
                  "U must be the same as T");

函数is_same() 即判断T与U的类型是否一致。
decay_t() cppreference 中以下6个判断均为true ,他会去掉const ,指针,和引用(包括左右值)属性来判断

int main()
{
    std::cout << std::boolalpha
              << decay_equiv<int, int>::value << '\n'
              << decay_equiv<int&, int>::value << '\n'
              << decay_equiv<int&&, int>::value << '\n'
              << decay_equiv<const int&, int>::value << '\n'
              << decay_equiv<int[2], int*>::value << '\n'
              << decay_equiv<int(int), int(*)(int)>::value << '\n';
}

这是比较不错的办法,但实际上还是不可靠。List只是希望能够将左右值划分为一类,这样会使指针或者const类型相混淆。

本例可以使用如下办法完美解决

这是boost中的函数
#include <boost/type_traits/remove_cv_ref.hpp>

std::is_same<remove_cv_ref<T>, remove_cv_ref<U>>

意为仅去除引用属性

最后 iter还是有未解决的bug):

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值