J
J
Does anyone know how to do this in C++ or if it can be done?
And also to find out how many fields there are in a struct?
And also to find out how many fields there are in a struct?
J said:Does anyone know how to do this in C++ or if it can be done?
And also to find out how many fields there are in a struct?
John Harrison said:It can be done with very crude casting and pointer arithmetic, but its
definitely a bad idea.
That cannot be done.
Almost certainly you are trying the wrong approach, either you need to
change your approach or you need to change your language. Why not explain
what you are actually trying to achieve and better advice can be given.
john
J said:Does anyone know how to [access the fields of a struct by position rather than name]
in C++ or if it can be done?
Perhaps something like this, I'm assuming that all your fields are int's
struct Base
{
virtual ~Base() {}
virtual int num_fields() = 0;
virtual int get_field(int n) = 0;
virtual void set_field(int n, int val) = 0;
};
struct Pair : public Base // a struct with two fields
{
virtual int num_fields() { return 2; }
virtual int get_field(int n)
{
if (n == 0)
return first;
else if (n == 1)
return second;
else
error("not enough fields");
}
virtual void set_field(int n, int val)
{
if (n == 0)
first = val;
else if (n == 1)
second = val;
else
error("not enough fields");
}
int first;
int second;
};
That's how you'd do it in C++, if you really have to do it at all.
john
J said:This is what I am looking for but I was hoping C++ would have the
features built in, rather than having to extend the structures.
Have you heard of Tuples? Could something similar also be done with
Tuples?
J
There's a very sophisticated Tuple implementation in the Loki library, it
allows any arbitary number and type of fields. Everything is worked out at
compile time instead of runtime like my crude code.
http://sourceforge.net/projects/loki-lib/
Boost also have a tuple library, don't know anything about that however.
http://www.boost.org/
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.