User loginNavigation |
Implementing arraysI got to thinking that it would be cool if using a language's builtin tools you could create its array type -- without using its array type. Most language's I've seen have some builtin concept of an array or list. And although some languages give a 'definition' of what a list is -- that defining code won't actually run through the interpreter. I came up with the following C++ implementation that manages to implement an array type without actually using arrays. Before you cry that it depends on the class layout which isn't guarunteed -- it is when a class is a POD, and in this case the element is public so it is, and even if it wasn't, it's a defacto standard that things are layed out this way and projects like boost.python depend on it, and the point of the example is to show that a language can do it (even if the language is "C++ with small tweak").
template<class T, int n>
class Array : public Array<T, n-1>
{
public:
T& operator[](int i);
T tail;
};
template<class T, int n>
T& Array<T, n>::operator[](int i)
{
// Should be able to just use line below
// but some compilers (GCC 3.4) are stupid
// return *(&(Array<T, 1>::mem) + i);
int& x = Array<T, 1>::tail;
return *(&x + i);
}
int main(int argc, char *argv[])
{
Array<int, 5> x;
cout << sizeof(Array<int, 5>) << endl; // 20 as expected
x[0] = 9;
x[1] = 8;
x[2] = 4;
x[3] = 2;
x[4] = 5;
// Prints correctly
cout << x[0] << x[1] << x[2] << x[3] << x[4] << endl;
return 0;
}
How often do you see recursive inheritance? *grin* By dataangel at 2006-08-27 06:27 | LtU Forum | previous forum topic | next forum topic | other blogs | 8879 reads
|
Browse archives
Active forum topics |
Recent comments
3 weeks 6 days ago
4 weeks 6 hours ago
4 weeks 1 day ago
4 weeks 1 day ago
4 weeks 6 days ago
4 weeks 6 days ago
4 weeks 6 days ago
8 weeks 4 hours ago
8 weeks 5 days ago
8 weeks 5 days ago