c++中std::initializer_list模板

#include "iostream"
#include "iterator"
#include "vector"
#include "map"
using namespace std;

template <typename T, class T2>
bool compare(T &v1, T2 &v2)
{
    return v1 > v2;
}

//费类型参数模板
template <unsigned N, unsigned M>
void comp(char (&a)[N], char (&b)[M])
{
    std::cout << end(a) - begin(a) << std::endl;
    std::cout << end(b) - begin(b) << std::endl;
    a[0] = 92;
}

template <typename T>
class B
{
  public:
    typedef T t;
    //嵌套从属名称std::vector::iterator的形式必须用typename指明
    typedef typename std::vector<T>::size_type type_v;

  private:
    //嵌套从属名称T::iterator的形式必须用typename指明
    typename std::vector<T>::size_type len = 0;
    std::map<int, std::vector<T>> mMap;
};

template <typename T>
class Father
{
  public:
    template <typename S>
    Father(S s1, S s2);
};



int main()
{

    double a = 837.7;
    int b = 32;
    std::cout << compare(a, b) << std::endl;
    std::cout << compare(b, a) << std::endl;

    char aa[5];
    char bb[89];
    comp(aa, bb);


    std::vector<int> v1 = {1,2,3,4};
    std::vector<int> v2{v1};

    v2[2] = 829;
    std::cout << "v1 " << v1[2] << " v2 = " << v2[2] << std::endl;

    std::initializer_list<int> l1 = {7,8,9};
    std::initializer_list<int> l2(l1);

    for (auto a : l2){
        std::cout << "a = " << a << std::endl;
    }
    
    for (int i = 0; i < l2.size(); i++){
        std::cout << "i =  " << i <<" v = "<< *(l2.begin() + i)  << std::endl;
    }
    return 0;
}

结果:

$ ./a.exe
1
0
5
89
v1 3 v2 = 829
a = 7
a = 8
a = 9
i =  0 v = 7
i =  1 v = 8
i =  2 v = 9

猜你喜欢

转载自blog.csdn.net/wulong710/article/details/81476284