Created
January 23, 2015 02:02
-
-
Save kahunamoore/a54a8c030167c5bd669f to your computer and use it in GitHub Desktop.
C++ Generic Initializer List
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
// from: http://stackoverflow.com/questions/15848781/constructor-for-nested-initializer-lists | |
template <int d, typename T> | |
class ClassA { | |
size_t n_[d] = {0}; | |
T* data_; | |
template <int D, typename U> | |
struct Initializer_list { | |
typedef std::initializer_list<typename Initializer_list<D-1,U>::list_type > list_type; | |
Initializer_list(list_type l, ClassA& a, size_t s, size_t idx) { | |
a.n_[d-D] = l.size(); | |
size_t j = 0; | |
for (const auto& r : l) | |
Initializer_list<D-1, U> pl(r, a, s*l.size(), idx + s*j++); | |
} | |
}; | |
template <typename U> | |
struct Initializer_list<1,U> { | |
typedef std::initializer_list<T> list_type; | |
Initializer_list(list_type l, ClassA& a, size_t s, size_t i) { | |
a.n_[d-1] = l.size(); | |
if (!a.data_) | |
a.data_ = new T[s*l.size()]; | |
size_t j = 0; | |
for (const auto& r : l) | |
a.data_[i + s*j++] = r; | |
} | |
}; | |
typedef typename Initializer_list<d,T>::list_type initializer_type; | |
public: | |
// initializer list constructor | |
ClassA(initializer_type l) : data_(nullptr) { | |
Initializer_list<d, T> r(l, *this, 1, 0); | |
} | |
size_t size() const { | |
size_t n = 1; | |
for (size_t i=0; i<4; ++i) | |
n *= n_[i]; | |
return n; | |
} | |
friend std::ostream& operator<<(std::ostream& os, const ClassA& a) { | |
for (int i=0; i<a.size(); ++i) | |
os<<" "<<a.data_[i]; | |
return os<<endl; | |
} | |
}; | |
int main() | |
{ | |
ClassA<4, double> TT = { {{{1.}, {7.}, {13.}, {19}}, {{2}, {8}, {14}, {20}}, {{3}, {9}, {15}, {21}}}, {{{4.}, {10}, {16}, {22}}, {{5}, {11}, {17}, {23}}, {{6}, {12}, {18}, {24}}} }; | |
cout<<"TT -> "<<TT<<endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment