C++之template template parameter、基于范围的for循环学习

1)模板模板参数学习,主要是为了让自定义容器也是泛型;
代码如下:

#include <iostream>
#include <list>

using namespace std;

// template template parameter 模板模板参数
template <typename T,
          template<typename> class container> //存储的是容器类型
//template <typename> class container说明XCls的第二个模板参数是一个模板类,当使用XCls的时候,需要为它指定一个模板参数
class XCls
{
private:
    container<T> c;
public:

};

//因为需要使用容器,所以为它指定了一个模板参数;
template<typename T>
using Lst = list<T>;

int main(void)
{
    XCls<string,Lst> mylist2;
    return 0;
}

在实际的开发中,可以使用template template parameter这种编程技巧把不同功能的模板类组合起来。

2)基于范围的for循环学习:

for循环格式:
for(declaration : expression )  //注意,用的是冒号":"
{
		循环体;
}

测试代码如下:

#include <iostream>
#include <list>

using namespace std;

int main(void)
{
    list<int> l{1,3,4,5,6};

    for(auto it : l) //这样是值拷贝,最好是引用,按下面注释的写
    {
        cout<<it<<" ";
    }

//    for(auto& it : l)
//    {
//        cout<<it<<" ";
//    }
    cout<<endl;
    return 0;
}

输出结果:

1 3 4 5 6
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值