Skip to content

Instantly share code, notes, and snippets.

@juehan
Created November 10, 2012 00:53
Show Gist options
  • Save juehan/4049306 to your computer and use it in GitHub Desktop.
Save juehan/4049306 to your computer and use it in GitHub Desktop.
C++11: Uniform Initialization
/*
* Uniform Initialization: C++11
* compiled under g++4.7.2
* */
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
template<typename C>
void Print(const C& c)
{
for(auto it = begin(c); it != end(c); ++it)
cout<<*it<<" ";
cout<<endl;
}
template<typename T>
void Print2(initializer_list<T> vals)
{
for(auto it = vals.begin(); it != vals.end(); ++it)
cout<<*it<<" ";
cout<<endl;
}
template <typename T>
class Print3
{
vector<T> _list;
public:
Print3(T a, T b){
cout<<"Print3::Print3(T,T) called"<<endl;
_list.push_back(a);
_list.push_back(b);
}
Print3(initializer_list<T> l) {
cout<<"Print3::Print3(initializer_list<T>) called"<<endl;
for_each(begin(l), end(l), [&](T n){
_list.push_back(n);
});
}
};
int main(int argc, char **argv)
{
int arr1[]{1,2,3,4,5};
Print(arr1);
vector<string> arr2{"hello","world","beautiful","c++11", "world"};
Print(arr2);
vector<int> arr3{6,7,8,9,10};
Print(arr3);
Print2({2,4,6,8,10}); //arr4
Print2({"say","hello","to","john"}); //arr5
Print3<int> arr6(10,11); //constructor called
Print3<int> arr7{21,22}; //initializer_list called
Print3<int> arr8 = {31,32,33,34}; //initializer_list called
Print3<int> arr9 = {41,42}; //initializer_list called
return 0;
}
/* output
1 2 3 4 5
hello world beautiful c++11 world
6 7 8 9 10
2 4 6 8 10
say hello to john
Print3::Print3(T,T) called
Print3::Print3(initializer_list<T>) called
Print3::Print3(initializer_list<T>) called
Print3::Print3(initializer_list<T>) called
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment