具有某种条件的宏
我正在尝试创建一个宏,这样我就可以避免某些输入,并使其更好/更容易地定义属性,这就是我的想法:
#define DefineProperty(Access, Type, Name) \
property<Access, Type> ##Name; \
void Set##Name(Type); \
Type Get##Name(void); \
其中 Access 是一个具有三个可能值的枚举:ReadOnly、WriteOnly 和 ReadWrite。仅当访问值适合该方法时才应定义宏中的方法。
这是否有可能以任何方式(例如使用元编程)实现?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以相当轻松地完成此操作:
宏替换如下所示:
Yes, you can accomplish this fairly easily:
The macro replacement takes place as follows:
麦克内利斯的回答相当直接和简单。但是,如果您有兴趣,也很有可能使用模板元编程来构建您想要的内容。去年我一直在完善一个库来做到这一点。
我不能全部分享,它是专有的,不属于我所有。但我可以向您指出我发现最容易使用的方向。查看 Abrahams 和 Gurtovoy 的《C++ 模板元编程》第 9.5 节中描述的技术。将其与 boost::tuple 和 boost::fusion 对象进行比较。请注意,您可以通过定义新类型来声明“名称”。因此,您可以创建您可能会使用的东西,如下所示:
我的系统实际上允许您定义这样的对象,其属性由函数实现。但它要复杂得多,我还没有找到一种方法将其简化到上述程度。为此,我从一篇名为“通过模板元编程实现反射支持”的文章开始,该文章位于网络上的某处……可能是从 ACM 中提取的。
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:
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.