C++: Convert Macro based Property System to use templates

cdesign-patternsmacrospropertiestemplates

I've already implemented, using macros, a C++ property system that satisfied the following requirements:

  • Property can be referenced using a integeral key
  • Property can be accessed via a generic Set/Get
  • Properties (and property keys) must be inheritable
  • Properties can be registered with getters/setters

and is implemented as follows

  • Each property belongs to a class
  • Each property is 'declared' with a key unique to it's inheritance chain. (Implemented using a rather clever __ COUNTER __ hack). It has the following characteristic
    • A root class (no parents) start numbering its properties from 0
    • A child class will start numbering its properties from the parent's last id + 1

class A
{    
    static const unsigned int Property_0 = GET_KEY_MACRO; //expands to 0
    static const unsigned int Property_1 = GET_KEY_MACRO; //expands to 1     
};
class B : public A
{    
    static const unsigned int Property_0 = GET_KEY_MACRO(A); //expands to 2
    //and so forth    
};
class C : public A
{
     static const unsigned int Property_0 = GET_KEY_MACRO(A); //expands to 2. different inheritance chain
};

  • Other code can refer to the property using the static constant id.

objectinstance.SetValue(C::Property_0, 5)

  • Each property is 'registered' by using a macro that expands to a virtual method. The macro currently allows for a property type, a getter, and a setter to be registered

BEGIN_PROPERTIES
    REG_PROP(Property_0, int)
    REG_PROP_G(Property_1, int, getterFunc)
    ...
END_PROPERTIES

//expands to 

virtual void registerProperties()
{
    register(blah, blah, ...)
}

  • SetValue/GetValue that takes a property key and does some background magic to set/get it(already implemented)

Can anyone think of template based approach that's equivalent/simpler to the above system?

Note: This property system is to designed for remote RPCish calls as well as fast local access.

Best Answer

This looks like a classic game property system so I'm going to recommend you read this Gamasutra article about a good system that doesn't require too much gunk around your code. Also have a look at boost.fusion and see if it can't help you.

What follows is my opinion and can be ignored for the sake of the question:

That said I'm not really sure what you'd gain by using templates. Is it just that "Macros Are Bad"?

Having worked with a bunch of these systems I've come to the conclusion that you're often solving the wrong problem by adding a property system. If you can, consider using a language like C# where properties are first-class language feature.

Related Topic