Macro with some sort of condition
I'm trying to create an macro so safe me from some typing and make it nicer/easier to define an property, this is what I have in mind:
#define DefineProperty(Access, Type, Name) \
property<Access, Type> ##Name; \
void Set##Name(Type); \
Type Get##Name(void); \
Where Access is an enum with three possible values: ReadOnly, WriteOnly and 开发者_高级运维ReadWrite. The method in the macro should only be defined if the access value is appropriate for the method.
Is this in any way possible for example using meta-programming?
Yes, you can accomplish this fairly easily:
#define DefineGetReadOnly(Name, Type) Type Get##Name();
#define DefineGetReadWrite(Name, Type) Type Get##Name();
#define DefineGetWriteOnly(Name, Type)
#define DefineProperty(Access, Type, Name) \
DefineGet##Access(Name, Type)
The macro replacement takes place as follows:
DefineProperty(ReadOnly, int, Foo)
DefineGetReadOnly(Foo, int)
int GetFoo();
DefineProperty(WriteOnly, int, Bar)
DefineGetWriteOnly(Bar, int)
/* no tokens */
Well, McNellis's answer is fairly straightforward and simple. But, if you're interested, it is quite possible to build exactly what you're after using template metaprogramming as well. I've been refining a library to do just that for the last year.
I can't share it all, it's proprietary and not owned by me. But I can point you in the direction I found to be the easiest to use. Check out the techniques described in 9.5 of C++ Template Metaprogramming by Abrahams and Gurtovoy. Compare it to things like boost::tuple and boost::fusion objects. Note that you can declare "names" by defining new types. Thus you can create something you might use like so:
struct object_with_properties : construct_property_object< mpl::vector< mpl::pair< property<access,type>, name> ... > >::type
{};
object_with_properties owp;
get<name>(owp);
set<name>(owp, value);
// or maybe
get<name>(owp) = value;
My system actually allows you to define such objects that's properties are implemented by functions. It's much more complex though and I've not found a way to simplify it to the above degree. For that I started with an article called "Reflection support by means of template metaprogramming" that's out on the net somewhere...might have pulled it from ACM.
精彩评论