Created
January 15, 2013 11:01
-
-
Save duckie/4537896 to your computer and use it in GitHub Desktop.
C++11 initiliazer_list example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <initializer_list> | |
struct Point { | |
int m_a; | |
int m_b; | |
Point() : | |
m_a(0), m_b(0) { | |
} | |
Point(int a, int b) : | |
m_a(a), m_b(b) { | |
} | |
}; | |
template<typename T> class ObjectInitializer { | |
T * m_tab; | |
public: | |
ObjectInitializer(const std::initializer_list<T> & x) { | |
size_t index = 0; | |
m_tab = new T[x.size()]; | |
for (auto i = x.begin(); i != x.end(); i++) { | |
m_tab[index++] = *i; | |
} | |
} | |
operator T*() { | |
return m_tab; | |
} | |
}; | |
int main(int argc, char * argv[]) { | |
Point * pTableau = ObjectInitializer<Point>({ Point(1,2), Point(3,4), Point(6,4), Point(8,6) }); | |
for(int i = 0; i< 4; i++) { | |
std::cout << "Point(" << pTableau[i].m_a << ',' << pTableau[i].m_b << ')' << std::endl; | |
} | |
delete [] pTableau; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment