473,748 Members | 2,461 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to instantiate array of objects knowing its indices at compiletime?

Hi,

the subject says it all: I need to instantiate an array of objects
where each object "knows" its arrary index. So far, this is easy
as long as index is not a compile-time constant:

class Elements {
public:
Elements():
index(maxIndex) {
maxIndex++;
}
const unsigned int index;
private:
static unsigned int maxIndex;
};
unsigned int Elements::maxIn dex = 0;
Elements array[5];

#include <stdio.h>
template<unsign ed int xstruct Test {
};
int main(void) {
printf("%d\n", array[4].index);
printf("%d\n", array[2].index);
// No way to create an instance
// of Test<with index.
}

The point is that I need to use index inside Element as a template
parameter constant, i.e index must be known for each Element instance
at compile time already.

Soemthing like this does work, but does not help as access to the
instances of Element cannot be done in a unique fashion by just
providing index:

template<unsign ed int istruct Array {
class Element {
public:
static const unsigned int index = i;
};
static Array<i - 1array;
};
template<struct Array<0{
class Element {
public:
static const unsigned int index = 0;
};
};

#include <stdio.h>
template<unsign ed int xstruct Test {
};
int main(void) {
printf("%d\n", Array<4>::Eleme nt::index);
printf("%d\n", Array<4>::Array <3>::Array<2>:: Element::index) ;
Test<Array<4>:: Array<3>::Eleme nt::indextest;
}

Any ideas how this problem could be solved?

Thanks for any help,

Christof
Aug 8 '08 #1
7 2947
Christof Warlich wrote:
the subject says it all: I need to instantiate an array of objects
where each object "knows" its arrary index. So far, this is easy
as long as index is not a compile-time constant:

class Elements {
public:
Elements():
index(maxIndex) {
maxIndex++;
}
const unsigned int index;
private:
static unsigned int maxIndex;
};
unsigned int Elements::maxIn dex = 0;
Elements array[5];

#include <stdio.h>
template<unsign ed int xstruct Test {
};
int main(void) {
printf("%d\n", array[4].index);
printf("%d\n", array[2].index);
// No way to create an instance
// of Test<with index.
}

The point is that I need to use index inside Element as a template
parameter constant, i.e index must be known for each Element instance
at compile time already.
But that would make every Element a unique type (at the first glance,
anyway)! And that would mean you can't convert between them (unless you
make them all descendants of each other, which is ugly) or put them all
in the same collection/container...
[..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 8 '08 #2
Victor Bazarov schrieb:
But that would make every Element a unique type (at the first glance,
anyway)! And that would mean you can't convert between them (unless you
make them all descendants of each other, which is ugly) or put them all
in the same collection/container...
You are right, but I could live with that, i.e. I do not need to convert
between them.

But what I need is some usable indexing:
Array<4>::Array <3>::Array<2>:: Element::index is not a working solution
to access the value of index 2.
Aug 8 '08 #3
Christof Warlich wrote:
Victor Bazarov schrieb:
>But that would make every Element a unique type (at the first glance,
anyway)! And that would mean you can't convert between them (unless
you make them all descendants of each other, which is ugly) or put
them all in the same collection/container...

You are right, but I could live with that, i.e. I do not need to convert
between them.

But what I need is some usable indexing:
Array<4>::Array <3>::Array<2>:: Element::index is not a working solution
to access the value of index 2.
Can you show how you'd like to use the indexing? I know it's not
working, but I would need to see what interface you're looking for.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 8 '08 #4
Victor Bazarov wrote:
Christof Warlich wrote:
>Victor Bazarov schrieb:
>>But that would make every Element a unique type (at the first glance,
anyway)! And that would mean you can't convert between them (unless
you make them all descendants of each other, which is ugly) or put
them all in the same collection/container...

You are right, but I could live with that, i.e. I do not need to convert
between them.

But what I need is some usable indexing:
Array<4>::Arra y<3>::Array<2>: :Element::index is not a working solution
to access the value of index 2.

Can you show how you'd like to use the indexing? I know it's not
working, but I would need to see what interface you're looking for.
OK, I thought of something, but this might be more complicated than you
need:

#include <iostream>
#include <ostream>

template<unsign ed s, class Tstruct ArrayOf;

template<class Tstruct ArrayOf<0,T{}; // empty

template<class T, unsigned indstruct ArrayElement
{
enum { index = ind };
T data;
ArrayElement() : data() {} // requires T to be default-consructible
ArrayElement(T d) : data(d) {} // requires T to be copy-constructible
};

template<class Tstruct ArrayOf<1,T>
{
ArrayElement<T, 0element; // will be default-constructible

T operator[](unsigned) const { return element.data; }
T& operator[](unsigned) { return element.data; }
};

template<unsign ed size, class Tstruct ArrayOf
{
enum { lastindex = size-1 };
ArrayElement<T, lastindextail;
ArrayOf<size-1,Thead;

T operator[](unsigned i) const {
if (i < lastindex)
return head.operator[](i);
else
return tail.data;
}

T& operator[](unsigned i) {
if (i < lastindex)
return head.operator[](i);
else
return tail.data;
}
};

int main() {
ArrayOf<10,intm yArrayOf10ints;

for (int i = 0; i < 10; ++i)
myArrayOf10ints[i] = i+42;

for (int j = 3; j < 8; ++j)
std::cout << "# " << j;
std::cout << " is " << myArrayOf10ints[j] << std::endl;
}

This, of course, creates 20 different types (arrays of all sizes from 1
to 10, and elements with all different indices from 0 to 9). I imagine
that if you need an array of 1000 elements, your compiler might choke on
the compilation recursion.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 8 '08 #5
Victor Bazarov schrieb:
OK, I thought of something, but this might be more complicated than you
need:
......
int main() {
ArrayOf<10,intm yArrayOf10ints;

for (int i = 0; i < 10; ++i)
myArrayOf10ints[i] = i+42;

for (int j = 3; j < 8; ++j)
std::cout << "# " << j;
std::cout << " is " << myArrayOf10ints[j] << std::endl;
}
Hi Victor,

thanks a lot for your help and sorry for the very late reply.
Unfortunately, this is not solving my problem of getting compile-time
constants by index.

Again, to illustrate what I'd need to do, I've slightly extended your
example. The key is to be able to pass the "array" value as a template
parameter, whatever object "array" might be:

......
template <unsigned int xstruct Test {
};
int main() {
ArrayOf<10,intm yArrayOf10ints;

for (int i = 0; i < 10; ++i)
myArrayOf10ints[i] = i+42;

for (int j = 3; j < 8; ++j) {
std::cout << "# " << j;
std::cout << " is " << myArrayOf10ints[j] << std::endl;
}
Test test<myArrayOf1 0ints[5]>;
}

$ g++ constArray.cc
constArray.cc: In function 'int main()':
constArray.cc:5 8: error: 'myArrayOf10int s' cannot appear in a
constant-expression
constArray.cc:5 8: error: an array reference cannot appear in a
constant-expression
constArray.cc:5 8: error: template argument 1 is invalid
constArray.cc:5 8: error: invalid type in declaration before ';' token

It's clear to me that this cannot compile: The "array" must be
a compile time constant itself. My second example in the first
post fulfilled this requirement, but only at the cost of the
clumsy access, i.e.

Test<Array<4>:: Array<3>::Eleme nt::indextest;

to acess the 3rd element, while I would need a solution where it
is sufficient to just pass in a 3 to get the 3rd element.

Note that logically, the index from my (second) example of my initial
post would correspond to the array values from your example. Therefore,
my example may have been a bit confusing as I was choosing my "array"
values to be equal to the index of that "array". This was due to my
original intention of knowing an instance's array index inside the
instance. But more generally, the problem boils down to:

template<unsign ed int istruct Array {
class Element {
public:
static const unsigned int value = i + 42;
};
static Array<i - 1array;
};
template<struct Array<0{
class Element {
public:
static const unsigned int value = 42;
};
};

#include <stdio.h>
template<unsign ed int xstruct Test {
};
int main(void) {
printf("%d\n", Array<4>::Eleme nt::value);
printf("%d\n", Array<4>::Array <3>::Array<2>:: Element::value) ;
Test<Array<4>:: Array<3>::Eleme nt::valuetest;
}

Anyhow, maybe a solution for this problem simply does not exist.

Cheers,

Christof
Aug 9 '08 #6
On 9 août, 09:52, Christof Warlich <cwarl...@gmx.d ewrote:
Victor Bazarov schrieb:
OK, I thought of something, but this might be more complicated than you
need:
.....
int main() {
* *ArrayOf<10,int myArrayOf10ints ;
* *for (int i = 0; i < 10; ++i)
* * * myArrayOf10ints[i] = i+42;
* *for (int j = 3; j < 8; ++j)
* * * std::cout << "# " << j;
* * * std::cout << " is " << myArrayOf10ints[j] << std::endl;
}

Hi Victor,

thanks a lot for your help and sorry for the very late reply.
Unfortunately, this is not solving my problem of getting compile-time
constants by index.

Again, to illustrate what I'd need to do, I've slightly extended your
example. The key is to be able to pass the "array" value as a template
parameter, whatever object "array" might be:

.....
template <unsigned int xstruct Test {};

int main() {
* * ArrayOf<10,intm yArrayOf10ints;

* * for (int i = 0; i < 10; ++i)
* * * *myArrayOf10int s[i] = i+42;

* * for (int j = 3; j < 8; ++j) {
* * * *std::cout << "# " << j;
* * * *std::cout << " is " << myArrayOf10ints[j] << std::endl;
* * }
* * Test test<myArrayOf1 0ints[5]>;

}

$ g++ constArray.cc
constArray.cc: In function 'int main()':
constArray.cc:5 8: error: 'myArrayOf10int s' cannot appear in a
constant-expression
constArray.cc:5 8: error: an array reference cannot appear in a
constant-expression
constArray.cc:5 8: error: template argument 1 is invalid
constArray.cc:5 8: error: invalid type in declaration before ';' token

It's clear to me that this cannot compile: The "array" must be
a compile time constant itself. My second example in the first
post fulfilled this requirement, but only at the cost of the
clumsy access, i.e.

Test<Array<4>:: Array<3>::Eleme nt::indextest;

to acess the 3rd element, while I would need a solution where it
is sufficient to just pass in a 3 to get the 3rd element.

Note that logically, the index from my (second) example of my initial
post would correspond to the array values from your example. Therefore,
my example may have been a bit confusing as I was choosing my "array"
values to be equal to the index of that "array". This was due to my
original intention of knowing an instance's array index inside the
instance. But more generally, the problem boils down to:

template<unsign ed int istruct Array {
* * *class Element {
* * * *public:
* * * * *static const unsigned int value = i + 42;
* * *};
* * *static Array<i - 1array;};

template<struct Array<0{
* * *class Element {
* * * *public:
* * * * *static const unsigned int value = 42;
* * *};

};

#include <stdio.h>
template<unsign ed int xstruct Test {};

int main(void) {
* * *printf("%d\n", Array<4>::Eleme nt::value);
* * *printf("%d\n", Array<4>::Array <3>::Array<2>:: Element::value) ;
* * *Test<Array<4>: :Array<3>::Elem ent::valuetest;

}

Anyhow, maybe a solution for this problem simply does not exist.
Hi,

**** CODE ****

#include <iostream>
template <int INDEX>
struct ComputeElement {
static const int value = INDEX + 42 ;
};
template < int I, int J=0 // two int parameters needed to get the
correct index
struct ArraySize : public ComputeElement< J {
typedef ArraySize< I, J+1 next;
};

template < int J >
struct ArraySize< J, J : public ComputeElement< J{};
template < int INDEX, class T = ArraySize<10
struct Array {
static const int value = Array < INDEX-1,
typename T::next >::value;
};

template < class T >
struct Array < 0, T {
static const int value = T::value;
};
int main()
{
std::cout << Array< 0 >::value ; // first element
std::cout << Array< 9 >::value ; // last element
}

**** /CODE ****

Alexandre Courpron.

Aug 9 '08 #7
co******@gmail. com schrieb:
On 9 août, 09:52, Christof Warlich <cwarl...@gmx.d ewrote:
>Anyhow, maybe a solution for this problem simply does not exist.

Hi,

**** CODE ****

#include <iostream>
template <int INDEX>
struct ComputeElement {
static const int value = INDEX + 42 ;
};
template < int I, int J=0 // two int parameters needed to get the
correct index
struct ArraySize : public ComputeElement< J {
typedef ArraySize< I, J+1 next;
};

template < int J >
struct ArraySize< J, J : public ComputeElement< J{};
template < int INDEX, class T = ArraySize<10
struct Array {
static const int value = Array < INDEX-1,
typename T::next >::value;
};

template < class T >
struct Array < 0, T {
static const int value = T::value;
};
int main()
{
std::cout << Array< 0 >::value ; // first element
std::cout << Array< 9 >::value ; // last element
}

**** /CODE ****

Alexandre Courpron.
Hi Alexandre,

wow, this is genius! It's exactly doing what I need, though I have
to admit that I'll need some time digesting the code to fully
understand how it works.

For now thanks a lot,

Christof
Aug 9 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2745
by: Michael Drumheller | last post by:
(If you're not interested in NumArray, please skip this message.) I am new to NumArray and I wonder if someone can help me with array-indexing. Here's the basic situation: Given a rank-2 array (i.e., a matrix) it seems to be trivial, with array indexing, to extract a subset of its *columns*. But it does not seem to be trivial to extract a subset of its *rows*. The code snippet below describes the problem (if it really is a problem)...
9
2129
by: Richard A. DeVenezia | last post by:
Can someone explain why JavaScript arrays are not allowed to have objects as indices ? Would solve many a hashtable lookup problems.... -- Richard A. DeVenezia
9
3440
by: Randell D. | last post by:
Folks, I can program fairly comfortably in PHP and can, for the most part using these skills and others that I've picked up over the years manage to read/understand most code in Javascript... so I'm just asking for a few pointers (or the full solution if you have the time) for what I want to do. Basically, I want to write a javascript wherby I only need to pass it the names of form fields - then my javascript will check each form field...
26
9632
by: JGH | last post by:
How can I check if a key is defined in an associative array? var users = new array(); users = "Joe Blow"; users = "John Doe"; users = "Jane Doe"; function isUser (userID) { if (?????)
5
2023
by: R. Rajesh Jeba Anbiah | last post by:
I could see that it is possible to have hash array using objects like var hash = {"a" : "1", "b" : "2"}; Couldn't still findout how to declare hash array in Array. var arr = new Array("a" : "1", "b" : "2"); doesn't work. Any hints? TIA -- <?php echo 'Just another PHP saint'; ?> Email: rrjanbiah-at-Y!com Blog: http://rajeshanbiah.blogspot.com/
22
4639
by: VK | last post by:
A while ago I proposed to update info in the group FAQ section, but I dropped the discussion using the approach "No matter what color the cat is as long as it still hounts the mice". Over the last month I had enough of extra proof that the cat doesn't hount mice anymore in more and more situations. And the surrent sicretisme among array and hash is the base for it. I summarized all points in this article:...
29
5470
by: shmartonak | last post by:
For maximum portability what should the type of an array index be? Can any integer type be used safely? Or should I only use an unsigned type? Or what? If I'm using pointers to access array elements as *(mptr+k) where I've declared MYTYPE *mptr; what should be the type of 'k'? Should it be ptrdiff_t?
204
13061
by: Alexei A. Frounze | last post by:
Hi all, I have a question regarding the gcc behavior (gcc version 3.3.4). On the following test program it emits a warning: #include <stdio.h> int aInt2 = {0,1,2,4,9,16}; int aInt3 = {0,1,2,4,9};
4
3660
by: Tomas | last post by:
A newbie question: How can I instantiate objects dynamically in VB.NET. E.g. I have the object 'Player' and I would like to instantiate it with the several instances (James, Gunner, etc.), without in advance knowing how many objects (employee1, employee2, etc) Dim player1 As New Persons.Players Dim player2 As New Persons.Players Dim player3 As New Persons.Players ....
0
8995
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8832
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9558
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9331
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6798
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4608
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3316
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.