Well, I am waiting on SO for goals like yours :D
In C++ we have std::array
and std::std::initializer_list
- so why not combine these two things together, to make this works:
int main() {
CArray<int, 7> a { E[1] = 13, E[6] = 14 };
for (int i = 0; i < 7; ++i) {
std::cout << a[i] << std::endl;
}
}
And produce this output:
0
13
0
0
0
0
14
So, where is magic?
Initialize std::array
from std::initializer_list<EIV_t<T>>
where:
template <class T>
struct EIV_t {
size_t i;
T v;
};
The new std::array:
template <class T, size_t N>
class CArray : private std::array<T,N> {
typedef std::array<T,N> Base;
public:
CArray() : Base() {}
CArray(std::initializer_list<T> l) : Base(l) {}
CArray(std::initializer_list<EIV_t<T>> l) : Base() {
for (auto i = l.begin(); i != l.end(); ++i) {
(*this)[i->i] = i->v;
}
}
// well, private inheritance has its cost
using Base::operator [];
// a lot of missing...
};
The rest of magic:
class EI_t {
public:
EI_t(size_t i) : i(i) {}
template <class T>
EIV_t<T> operator = (const T& v) const
{
return EIV_t<T> { i, v };
}
private:
size_t i;
};
class E_t {
public:
EI_t operator [] (size_t i) const { return EI_t(i); }
};
E_t E;
Full example: http://ideone.com/nzWL0