Is there a way to use an union in GLSL? - glsl

I was wondering if there is a way to use an union in GLSL. I haven't seen any documentation about this. If not, is there a clean workaround to using a union.
I basically want an array of something. And that something might be either of 2 things, therefore I would like to use a union to define it.
Thanks!
P.S. There might be some weird casting trick to do this that I don't know about, feel free to suggest a better method.
Edit:
Code example(would not compile because union is not available):
struct A{
bool isA;
float value;
};
struct B{
bool isA;
int value;
};
/* union */
union AandB {
A a;
B b;
}
void main()
{
AandB foo;
if(foo.a.isA)
/* process on A */
else
/* process on B */
}
Also, imagine A and B are huge, you wouldn't want to duplicate them.
Edit 2:
Here's some more information, hope it helps:
This data would come from "outside" and be vertex specific. It would have to be treated differently depending on the type(A or B). They'd probably be accessed from a VBO.

Since we are talking about vertex attributes, you can do this:
layout(location = 0) vec4 floatVal;
layout(location = 0) ivec4 intVal;
OpenGL refers to this as attribute aliasing, and it is explicitly allowed, with the following caveat. Either only one of the aliased attributes is accessed, or each code path through the shader only accesses one of the attributes. So if you guard the access and value computation with a boolean condition, you'll be fine:
//Don't use either variable yet
if(isFloat)
{
//Do something with `floatVal`
}
else
{
//Do something with `intVal`
}
//Don't use either variable again.
Well, you'll be fine theoretically. Attribute aliasing is a very odd corner-case, and it's highly unlikely that any major programs that use OpenGL actually do this. Which means that implementation support will likely be buggy (code that isn't used is code that hasn't been tested). So I would advise you to switch programs if you want to make sure your code actually works across platforms.

According to GLSL specification, the keyword union is reserved for future use and will indeed result in a compilation error.
One way around that would be supported by GLSL, since they encourage you to go with straightforward data structures (no evil pointer allocation or weird casting tricks), would be to use an array of struct with a flag.
struct AandB {
A a;
B b;
bool isA;
};
Then, you can use it has intended with something like this:
AandB foo;
if (a.isA) {
/* a process */
}
else {
/* b process */
}
However, if an item has the possibility of containing neither of the types, you should be careful with the fact that the flag will be initially false and assume type B. In that case, a workaround would be to use two flags and set the correct one.
UPDATE:
If memory usage is an issue, there is still a way around, but it needs a funnier data structure. One way that comes in mind is having an array of item definitions that will hold an index and a flag. Let's imagine this data structure:
struct Item {
bool isA;
int index;
};
Item items[5];
A a[5];
B b[5];
Item firstAItem;
firstItem.isA = true;
firstItem.index = 0;
items[0] = firstAItem;
Item firstBItem;
firstBItem.isA = false;
firstBItem.index = 0;
items[1] = firstBItem;
When iterating, you could check the flag and go to the associated index, like this, assuming that N_items is the number of items you have:
for (int i=0; i<N_items; i++) {
Item currentItem = items[i];
if (currentItem.isA) {
A foo = a[currentItem.index];
/* do some stuff with foo */
} else {
B bar = b[currentItem.index];
/* do some stuff with bar */
}
}

Related

Using different array-types interchangeably

I'm sure this question has been answered somewhere, but I'm not sure, what to even search for:
Say I have a class that stores some data in a std::vector, but I want to be able to use two differenct types interchangeably (for example to save memory) depending on the "mode" I set the class to. Something like this:
class MyClass
{
int Mode; // Could be, say, 0 or 1
std::vector<float> MyData; // Use this when Mode is 0
std::vector<short> MyData; // Use this when Mode is 1
void DoStuffWithData()
{
// ...
}
}
I know, this could probably be done with template, but I have not yet managed to wrap my head around this (if anybody could give me an example, please do so). Of course I could work with overloaded functions and use a lot of if-statements to switch between the cases or use a void-pointer that is set to one of the vectors and then cast to its type, but I think, this would make pretty messy code.
What would be a nice and clean way to use (mostly) the same code by just referring to MyData?
Edit
Mode would change during runtime. Basically the class would record and work with data it collects in the background. I want to be able to just change Mode for a new "recording" (of which I might start multiple during runtime). This would then set both vectors to size zero and use the one selected. Again - I know, I could overload functions and just use some if-statements, but I would like to keep the code short and clean (and maybe learn some things along the way).
You can't have two members called MyData. You can use templates instead, as that's essentially what they're meant for. This would be a simple example:
template<class T>
class MyClass {
std::vector<T> MyData;
void DoStuffWithData()
{
// ...
}
};
int main() {
MyClass<short> shortData;
MyClass<float> floatData;
MyClass<long> longData; // you're no longer limited to just two types
// ...
return 0;
}
Notice there's no Mode anymore, as you'll just choose the desired type when declaring each variable.

C++ How do I use a structure after I Zeroed its memory?

Hello when I Zeroed out the structure here
struct hudelem_color{ byte r, g, b, a; };
I cannot use it anymore so what would I do if I wanted to reuse it after i did
ZeroMemory(&hudelem_color, sizeof hudelem_color)
hudelem_color is a struct/type, you need to define an object for it.
hudelem_color clr;
ZeroMemory(&clr, sizeof (hudelem_color));
it's meaningless to memset a struct definition.
With your example structure
struct hudelem_color{ byte r, g, b, a; };
Then you can have e.g. this loop
bool game_continue = true;
while (game_continue)
{
hudelem_color color;
memset(&color, 0, sizeof(color));
// Use the `color` variable, do whatever you want with it
}
Each iteration of the loop you define a new instance of the structure, and zero the memory of it. This is not strictly reuse of the structure instance, as a new instance is created every iteration in the loop.
You can also have
hudelem_color color;
while (game_continue)
{
memset(&color, 0, sizeof(color));
// Use the `color` variable, do whatever you want with it
}
The above loop works almost as the previous one, but instead of creating a new instance every iteration one is created before the loop and then actually reused in each iteration.
I would personally recommend the first variant though. And if you do this, why not simple add a default constructor that clears out the fields, then you don't have to do it manually every iteration:
struct hudelem_color
{
byte r, g, b, a;
hudelem_color() : r(0), g(0), b(0), a(0) {}
};
// ...
while (game_continue)
{
hudelem_color color;
// Here all fields of the structure variable `color` will be zero
// Use the structure as you see fit
}
Sure, go for it. You can totally re-use it. after ZeroMemory you've got a hudelem_color with r,g,b, and a all zero. Just use it.
Some code that needs high performance while reusing thousands of little objects uses a pattern called 'object pools', google for more info...

C++ Struct - Define Minimum Size

Is there a C++ (or MSVC) method of automatically padding a struct to a minimum size? For example, imagine the following pseudo-code:
#pragma pad(256) // bytes
struct SETUPDATA {
int var1;
double var2;
};
where sizeof(SETUPDATA) = 256 bytes
The goal here being, during development this struct's members can change without changing the footprint size at runtime.
You can use a union
struct SETUPDATA {
union { struct your_data; char [256]; }
}
or something like this. This ensures it's at least 256 but only as long as your_data is not larger.
You can also add a simple assert after that just does a compiler check assert(sizeof(struct SETUPDATA) == 256)
One way is to inherit from your "real" structure and use sizeof() to make up the padded structure, for example:
struct blah_real
{
int a;
};
struct blah : public blah_real
{
private:
char _pad[256 - sizeof(blah_real)];
};
You could use #ifdef DEBUG to only do this in the debug build and just use the real structure in release build.
The first thing you have ot ask yourself is why your application cares if the struct size changes. That indicate fragility to future changes and your design may be better served by instead allowing the application to seamlessly work in the face of struct size changes.
Perhaps you're trying to serialize the data directly and don't want to face changes in the format, but in that case you're already tying yourself to one specific representation of the structure in memory. For example support the size of one of the builtin-type members changes due to a compiler upgrade or options.
But let's say you really do want to do this.
Just wrap the data in an impl and pad the real struct:
struct SetupData
{
struct Impl
{
int var1;
double var2;
};
Impl impl_;
unsigned char pad_[256 - sizeof(Impl)];
};

how to dynamically create methods to operate on class objects initialized at runtime

I have a class, say
class AddElement{
int a,b,c;
}
With methods to set/get a,b,c... My question is definitely a logic question - say I implement AddElement as follows:
int Value=1;
Value+=AddElement.get_a()+AddElement.get_b()+AddElement.get_b();
Now imagine I want to do the above except 'a,b,c' are now arrays, and instead of 'adding' I do scalar addition. At runtime sometimes I need 'a' but not 'b' or 'c', so I could rewrite as:
Value+=AddElement.get_a();
(Of course the += is overloaded to represent a scalar addition... and Value is the same size as a) - Other times I might only need b or c to be added etc...
Is there a way to go about selecting which elements, a,b,c, I want to initialize and later use at runtime? ( i.e. I don't want to malloc a huge array if I'm not going to use it).
In the end I need a class that has a,b,c and then methods that can operate on any combination of a,b, or c - having the user define what methods they need at runtime (via some kind of flag, or config file).
Currently I'm doing the following:
Value+=AddElement.get_a()*FlagA+AddElement.get_b()*FlagB+AddElement.get_c()*FlagC;
where FlagA=1 if you want to use 'a' in the addition or 0 if you don't want it to be included (The same for FlagB and FlagC). This is costly if the array 'a' is very large.
I'm probably just not thinking hard enough, but this problem has been bothering me. If you need me to better define the issue I will try, but I believe this is enough to get my point across.
Edit 2
I also forgot to add that I can't use any conditionals during the implementation of the addition (this is going to be used in a CUDA kernel and I can't have any thread diverngance - I was hoping to avoid mentioning CUDA since this is entirely a c++ question)
Edit 3
I believe what I need to do is use virtual functions. I want to call the function in the same manner, except have it execute a case specific function.
Edit 4
I would appreciate if someone took a look at my solution - maybe its too 'exotic' and there's a simpler method to accomplish the same end. Thanks for all the suggestions!
Edit 5
Thanks to another user I looked at the Strategic Design Pattern - and this is exactly the solution I used for this problem. I had never heard of that before and ended up rethinking a problem that has already been done (took a while for someone to mention something about it). So the solution:
Determine Algorithm at Runtime = Strategic Design Pattern.
You provide your class with a method GetSumOfActiveElements that does just what the name says. You can make this class virtual and create subclasses for each scenario, or have the class manage the memory efficiently in some other way.
What about something like this?
vector<pair<int, bool>> values(3);
values[0].first = 1;
values[0].second = false;
values[1].first = 2;
values[1].second = true;
values[2].first = 3;
values[2].second = false;
int sum = values[0].first * values[0].second +
values[1].first * values[1].second +
values[2].first * values[2].second;
You could probably make this cleaner/extensible using functors and <algorithm>.
It's not clear to me why conditionals are a bad thing - multiplication will be more expensive I would think. Is this a CUDA limitation or idiosyncracy?
If you allowed conditionals you could make your vector member a class that encapsulated a value and an in-use flag, and use filtering algorithms to perform aggregation as required.
Does this rough outline of code work for you?
struct S{
int getx() {return 0;}
int gety() {return 0;}
int getz() {return 0;}
};
int main(){
int (S::*p[3])(); // allocate as per need
p[0] = &S::getx; // populate as per need at run time
p[1] = &S::gety;
p[2] = 0;
int val = 1;
S obj;
int nCount = 0;
while(p[nCount] != 0)
val += (obj.*(p[nCount++]))();
}
EDIT 2: #Steve Townsend: That's right. I missed that conditional stuff.
How about this.
struct S{
int getx() {return 0;}
int gety() {return 0;}
int getz() {return 0;}
S(){}
S(S &obj, int (S::*p)()){
val += (obj.*p)();
}
static int val;
};
int S::val = 0;
int main(){
S obj;
S buf[] = {S(obj, &S::getx), S(obj, &S::gety)}; // the magic happens here in
// the constructor
}
So I think I got it -
struct S{
int x,y;
bool needx,needy;
};
class AnyFunction {
protected:
S Vals;
int TotalValue;
public:
virtual void SetValues(void) =0;
virtual void AddValues(void) =0;
}
class ImplementationFunc1 : public AnyFunction {
public:
void SetValues(S * Vals) { S.x=Vals->xval; }
void AddValues(void){ TotalValue+=Vals->x; }
}
class ImplementationFunc2 : public AnyFunction {
public:
void SetValues(S * Vals) {S.x=Vals->xval;S.y=Vals->yval;}
void AddValues(void){ TotalValue+=(Vals->x+Vals->y); }
}
int main(){
S SVals;
AnyFunction * APointerToAnyFunction;
// read a file that says if we need either x or y
SVals.needx=true; // (i.e. read from file)
SVals.needy=false; // (read from file)
if(Svals.needx){
SVals.x=Xfromfile;
if (Svals.needy){
ImplementationFunc2 Imp1;
SVals.y=yfromfile;
APointerToAnyFunction=&Imp1;
}
else{
ImplementationFunc1 Imp2;
APointerToAnyFunction=&Imp2;
}
}
...
// blah set some values
...
// So now I can call the function the same way (i.e. the call is always the same, no matter what kind of addition it needs to do), but I have all
// the logic for the conditions done _outside_ the addition
APointerToAnyFunction->AddValues();
So that should basically do it! no I can use the call: "APointerToAnyFunction->AddValues()" To perform the addition. The implementation can be determined by flags at the beginning of the program, then I can write a different class for each condition that i need to satisfy, and then have my polymorphic class inherit the properties of the base class.
Sorry if I did not fully define my problem, or the statement was vague - I didn't really know exactly how to do what I was explaining, but knew it was possible. Is this the right way to go about this? Is there a more efficient way?
Thanks to all who responded. Of course when x and y are arrays, I dynamically allocate x and y when necessary...
How about a std::vector of elements?
Problem spec is a bit unclear, to say the least, but I think that would work for you.
Cheers & hth.,

Accomplish this task in C++; Migration from AS3.0

I've got way too much information to work with, so for now I'll consider this question answered until I can sort it all out and decide on the final implementation! Thanks a ton gf and Simon Buchan. I wish I could accept both of your answers, since they're both definite possibilities!
Additional / Revised Conceptual Information as suggested:
What I am aiming to do;
I am making a game. In this game every object used is an instance of the DOBJ class. The TUR class extends the DOBJ class. The SHO class extends the TUR class.
Each TUR class has an array of SHO's stored in it's SHOARR array. Each SHO instance needs to be given a set of instructions.
I know for a fact I could make 1000's of different SHO classes that have their instructions set during construction.
However, considering I will have so many different acting SHO instances, I was interested in another way to pass a set of instructions. Through the contruction of the SHO would be the ideal.
The instructions I am attempting to pass to each SHO are simple if statements;
if(frame > 64) { rotation += 4; };
if(state == 0 && frame < 32) { xs = 12; ys = 12; state = 1; };
Original question
Migration from ActionScript3.0 to C++ is proving to be a trial indeed. Thanks to those who have answered my questions thus far and also to those who opened stackoverflow in the first place. Onto the question... (TL;DR near the bottom to get straight to the question)
I'm attempting to apply the same logic that I could apply in AS3.0 to my project in C++ and it's just not going very well.
In AS3.0 I was used to slapping any and every datatype into an Array. It made things pretty simple. Now that I've run into C++ dev, I realized that I can't exactly do that anymore.
So now I'm stuck with this problem of rewriting a little AI system in a new language, where the driving point of the system isn't even compatible!
Here's an example of a piece of the code I was writing in AS3.0;
AI[NUM][1]( OBJ, AI[NUM][2], AI[NUM][3] );
AI being an array, NUM being an integer, OBJ being an instance of a class.
This line obviously called the function in the second element of the first array in the main array with the arguments being a class in which to perform the function on, whatever was in the third element of the first array of the main array, and likewise the fourth element.
In this case;
AI[NUM][1] would be a function
AI[NUM][2] would be a variable
AI[NUM][3] would be a number
Generally, my AI was run on calling a function to change or compare the variable with a number.
An example would be;
CompareST( someObject, "x", 500 );
and return true if someObject's x variable was smaller than (ST) 500.
The AI array itself was just filled with arrays of calls similar to this.
Quite new to C++ I had no idea how to go about this, so I did a bit of searching and reading of many different websites and came to the conclusion that I should look into function pointers.
However, after reading a bit into them, I've come to the conclusion that it won't help me realize my goal. While it did help me call functions like I wanted to call them, it doesn't help me stack different datatypes into one large array of arrays.
TL;DR
EDIT++:
What I need for each object is a set of instructions to be checked every frame. However, for each instance of the class, the instructions have to be different.
I plan on having a LOT of different instances, so making a class for each one is unreasonable.
Thus, I needed a way to pass a set of instructions to each one through it's constructor and read + execute them at any time their think() function is called.
My ultimate goal (aside from finding out about a better way to go about this) would be to be able to have an array of function calls, like;
A[n][0]( O, A[n][1], A[n][2] );
Where;
O is the instance the function is altering
A[n][0] is a function (Equality or Comparison)
A[n][1] is the variable, eg; "x", O["x"] (or a pointer to that variable in the case of C++)
A[n][2] is the value to alter the variable by, or compare it to.
And I'm not sure how I would rewrite this into C++, or alter it to work in another way.
Aftermath / Additional Information
What I'm actually aiming to do is be able to give an object a set of instructions at the time of it's creation, through the constructor. For example upon creation give an object instructions to wait 64 frames, and then rotate in the opposite direction, would have been something like this;
t.AI = [ [ 1, AIF.CompareET, "STATE", 0, AIF.CompareGT, "FRAME", 64, 0, AIF.EqualityAT, "baseRotation", 180, AIF.EqualityET, "STATE", 1 ] ];
In pseudocode;
(The 1 in the array denotes how to read the rest of the array, in this case everything before the odd 0 [ The one that comes after 64 ] is a comparison. If any of those fail, anything after the 0 will not be looked at )
Compare STATE is equal to (ET) 0, if true
Compare FRAME is greather than (GT) 64, if true
Add 180 to (AT) baseRotation, Set STATE equal to 1
Sorry that this turned out really long. I hope it's understandable, and I'm not asking something stupidly difficult to explain.
You can store functions using function pointers or functors. Variant types though are not natively supported by C++, you have to use custom solutions there.
One possibility would be to use Boost.Any (or better, Boost.Variant if you only use a fixed set of types):
typedef void (*Function)(Object*, const std::string&, boost::any&);
std::vector<Function> functions;
Given some function:
void f(Object* obj, const std::string& name, boost::any& value) {
// ...
}
you could store and call it similar to your example:
functions.push_back(&f);
functions[0](obj, "x", boost::any(500));
To utilize a declarative syntax, there are three options that come to my mind:
you use a similar approach and have central "interpreter" function, e.g. based on a switch (don't forget to switch to integers or pointers-to-members instead of strings if you need performance)
you invent your own language and generate C++ code from description files
you compose function objects in a declarative way
To do composition, you could use Boost.Bind or something like custom objects that represent operations:
struct Operation {
virtual ~Operation() {}
virtual bool operator()(Object&) = 0;
};
template<class T>
struct GreaterThen : Operation {
typedef T Object::*Member;
Member member;
const T value;
CompareGT(Member member, const T& value) : member(member), value(value) {}
bool operator()(Object& obj) { return (obj.*member > value); }
};
template<class T>
struct SetTo : Operation {
typedef T Object::*member;
Member member;
const T value;
SetTo(Member member, const T& value) : member(member), value(value) {}
bool operator()(Object& obj) { obj.*member = value; return true; }
};
Now we can build operation lists:
typedef std::vector<Operation*> OpList;
OpList operation;
operations.push_back(new GreaterThen<int>(&Object::Frame, 64));
operations.push_back(new SetTo<int>(&Object::State, 1));
We can use helper functions to avoid having to specify the template types:
template<class T>
Operation* opGreaterThen(T Object::*mem, const T& val) {
return new GreaterThen<T>(mem, val);
}
Assuming a similar helper for SetTo and using Boost.Assign the above becomes:
OpList operations = boost::assign::list_of
(opGreaterThen(&Object::Frame, 64))
(opSetTo (&Object::State, 1));
Executing the operations becomes the following then:
OpList::iterator it = operation.begin();
for( ; it != operations.end(); ++it) {
Operation& op = *it; // just for readability
if(!op(someObject)) break; // stop if operation returns false
}
Wow.
Reading through that slowly suggests what you're trying to end up with is an array of function calls and you can choose a different function with the same parameters (but different implementation) for different actions and choose the correct one for the correct case.
If that is the case, you're looking for function pointers. Try this tutorial.
You should be able to use a function pointer with an argument set and point it to the correct function based on your needs. You won't need an array of function pointers for this either - any function that matches the definition should do. From the tutorial, declare a function pointer like this:
int (TMyClass::*functptr)(classname, int, int) = NULL; // C++
Then assign it later:
this.functptr = &TMyClass::doitthisway;
While it is possible (although a pain) to have an array of arbitrary types, you pretty much never need it, since you have to know something about what is where to do anything interesting with it: for example, your 'TL;DR' example seems to look something like:
struct AIRule {
// Can only handle comparing ints, see later for more general solution.
typedef bool compare_type(AIObject*, AIObject::*int, int);
compare_type* compare;
AIObject* object;
AIObject::int* member;
int comparand;
};
So now you can do something like:
bool ai_equal(AIObject* object, AIObject::int* member, int comparand) {
return object->*member == comparand;
}
...
ai[n].compare = &ai_equal;
ai[n].object = some_object;
ai[n].member = &AIObject::some_member;
ai[n].comparand = 50;
...
if (ai[n].compare(ai[n].object, ai[n].member, ai[n].comparand)) {
...
}
This just moves the any type problem from the rules array to member though. C++ needs to know at least how many bytes a member is, and a string (for example) can be much bigger than an int. You can get around this by using pointers: which essentially is C++'s version of any, but you then need to delete it yourself (or you will leak memory!), at which point the interface method below becomes simpler.
If I was doing what you seem to want, I would use inheritance:
struct Sprite {
int frame;
double rotation;
Sprite() {
frame = 0;
rotation = 0.0;
}
virtual ~Sprite() {}
virtual void think() {
++frame;
}
virtual void draw() {
...
}
};
struct RotatingSprite : public Sprite {
int state;
MyShape() {
state = 0;
}
void think() {
Sprite::think();
if (state == 0 && frame > 64) {
state = 1;
rotation += 180.0;
}
}
};
Or a function pointer:
struct Sprite {
int frame;
double rotation;
void (*think)(Sprite*);
Sprite() {
frame = 0;
rotation = 0.0;
}
};
void rotate_think(Sprite* sprite) {
if (sprite->state == 0 && sprite->frame > 64) {
sprite->state = 1;
sprite->rotation += 180.0;
}
}
...
sprite->think = &rotate_think;
If you really need to do it dynamically I would recommend using the ++ part of C++. For the predicates (a predicate is just something that returns a boolean, like isLowerCase()) create an AIPredicate interface, and the actions an AIAction interface:
struct AIPredicate {
// "When you delete an AIPredicate, delete the full type, not just this interface."
virtual ~AIPredicate() {}
// "You can treat this as a function (operator()) but I'm not providing an implementation here ( = 0)"
virtual bool operator()(AIObject* object) = 0;
};
struct AIAction {
virtual ~AIAction() {}
virtual void operator()(AIObject* object) = 0;
};
struct AIRule {
// std::auto_ptr (or std::unique_ptr if you can use C++0x) will delete predicate for you.
// Add "#include <memory>" to your includes if it complains (most std headers will include it already)
std::auto_ptr<AIPredicate> predicate;
std::auto_ptr<AIAction> action;
};
Now you can make types like:
struct AIFrame : public AIPredicate {
// Implement the operator() member AICondition promises.
bool operator()(AIObject* object) {
return object->foo < 100;
}
};
...
// Use .reset() instead of = if you use std::unique_ptr.
ai[n].predicate = new AIFooIsLow();
If you want to have a very general predicate type, you can use the very powerful (and complicated) templates feature:
// The naming convention I'm using here is 'T'TitleCase for template parameters, TitleCase for types,
// lower_case for arguments and variables and '_'lower_case for members.
template<typename TMemberType, AIObject::TMemberType* TMember>
struct AIMemberEquals : public AIPredicate {
// Constructor: Initializes a new instance after it is created.
AIMemberEquals(TMemberType comparand) {
// Save comparand argument so we can use it in operator().
_comparand = comparand;
}
bool operator()(AIObject* object) {
return object->*TMember == comparand;
}
// Stores the value to compare.
TMemberType _comparand;
};
Unfortunately, creating templates looks a bit crazy:
ai[n].predicate = new AIMemberEquals<int, &AIObject::some_member>(100);
Read it as "create a new instance of (the type that AIMemberEquals applied to int and (the some_member member of AIObject) creates), with the argument 100".
When you have multiple predicates memory management becomes a bit more difficult without C++0x's unique_ptr or shared_ptr, types that will delete the object for you, since std::auto_ptr doesn't work in containers:
#include <vector>
struct AIData {
// vector is fairly close to AS3's Array type, it is a good default for
// arrays of changing or unknown size.
std::vector<AIPredicate*> predicates;
// Destructor: will be run before the memory for this object is freed.
~AIData() {
for (int i = 0; i != predicates.size(); ++i) {
delete predicates[i];
}
}
};
...
ai[n].predicates.push_back(new AIFooIsLow());
...
for (int i = 0; i != ai[n].predicates.size(); ++i) {
(*ai[n].predicates[i])(ai[n].object);
}
In C++0x:
struct AIData {
// unique_ptr will delete it for you, so no ~AIData() needed.
std::vector<unique_ptr<AIPredicate>> predicates;
};
Your final example could in C++ look something like:
std::auto_ptr<Shape> shape(new Shape());
...
std::auto_ptr<AIRule> rule(new AIRule());
rule->predicates.push(new AIMemberEquals<int, &Shape::state>(0));
rule->predicates.push(new AIMemberGreater<int, &Shape::frame>(64));
rule->actions.push(new AIAddMember<double, &Shape::rotation>(180.0));
rule->actions.push(new AISetMember<int, &Shape::state>(1));
shape->ai.push(rule); // .push(std::move(rule)); if you are using unique_ptr
Certainly not as pretty, but it works and is fairly flexible.