生成代码时#define的最佳替代品是什么? [英] What would be the best replacement for #define when generating code?

查看:117
本文介绍了生成代码时#define的最佳替代品是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

生成代码时#define的最佳替代品是什么?



我们有一系列用于生成的宏(#define)代码



(简化)示例



What would be the best replacement for #define when generating code?

We have a series of macros (#define) that will be used to "generate" code

for (a simplified) example

#define SOME_CODE( name, defaultValue ) \
  if ( m_##name == defaultValue ) \
  { \
  // do something \
  }



将被调用




and will be called

SOME_CODE(radius, 33)
SOME_CODE(length, 42)
SOME_CODE(width, 69)







我们的实际SOME_CODE定义相对复杂(多个参数,创建循环...)



C ++中有更好的方法吗?




Our actual SOME_CODE define is relatively complex (multiple parameters, creates loops...)

Is there a better way in C++ to do that?

推荐答案

我只知道使用 C ++ 编译器的唯一其他技术是模板元编程(参见维基百科页面 [ ^ ])。

当然,您也可以使用外部工具生成 C ++ 源代码

(例如从 Lua 表生成 C ++ 代码。
The only other technique I am aware of, using just the C++ compiler, is template metaprogramming (see the Wikipedia page[^]).
Of course, you might also use an external tool to produce C++ source code
(e.g. generating C++ code from a Lua table).


问题是'n'你可以用什么来复制将代码符号拼接在一起的技术,但是首先找出你认为你需要它的原因,然后决定一种适当的,现代的方法来解决它。



也就是说,由于该示例似乎是关于简化设置功能,让我指向 __ declspec(属性) VisualStudio提供的声明。我不是一个大粉丝,部分是因为它是VS特定的,但也许它可以帮助你实现类似的东西: https://msdn.microsoft.com/en-us/library/yhfk0thd%28v=vs.120%29.aspx [ ^ ]
The question isn't so much what you can use to duplicate that technique of mashing code symbols together, but finding out why you thought you'd need it in the first place, and then decide on an appropriate, modern way to solve it.

That said, since the example seems to be about a 'simplified' set functionality, let me point you to the __declspec(property) statement that VisualStudio provides. I'm not a big fan, in part because it's VS-specific, but maybe it helps you achieve something similar: https://msdn.microsoft.com/en-us/library/yhfk0thd%28v=vs.120%29.aspx[^]


这篇关于生成代码时#define的最佳替代品是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆