使用宏来压缩代码
我正在基于 xml 文件实例化各种对象。为了从模板创建对象,我在 xml 文件中指定数据类型。由于我有很多应该支持的模板和数据类型,因此我想稍微压缩一下我的代码。我以为我可以通过使用宏来做到这一点,但由于我从未真正使用过它们,所以我不知道如何做到这一点。通过提供我想要支持的数据类型列表,我想我可以简单地编写
MACRO(A, dataTypes)
而不是:
if(s == "float")
{
return new A<float>(name);
}
else if(s == "int")
{
return new A<int>(name);
}
else if(s == "bool")
{
return new A<bool>(name);
}
else if(s == "std::string")
{
return new A<std::string>(name);
}
...
但是我如何定义这样的宏呢? 该代码也应该在 Android 上编译,因此它不应该依赖其他库(例如 boost)。
I am instantiating various objects based on an xml file. To create an object from a template I specify the datatype in the xml file. As I have quite a lot of templates and datatypes that should be supported I'd like to condense my code a little bit. I thought I could do this by using macros, but since I never really used to them, I have no idea how to do this. By providing a list of datatypes I'd like to support I thought I could simply write
MACRO(A, dataTypes)
instead of:
if(s == "float")
{
return new A<float>(name);
}
else if(s == "int")
{
return new A<int>(name);
}
else if(s == "bool")
{
return new A<bool>(name);
}
else if(s == "std::string")
{
return new A<std::string>(name);
}
...
But how can I define a macro like that?
The code should compile on Android as well, so it should not rely on another library like boost.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该宏类似于:
您只需要一个参数(类型),因为据我所知,
A
在您的代码中是固定的。如果您想同时创建多种类型的代码,这并不容易。您应该使用诸如 boost 预处理器之类的东西。
The macro would be something like:
You only need a parameter (the type), because as far as I can see,
A
is fixed in your code.If you want to create the code for several types at once, this is not that easy. You should use something like boost preprocessor.