通过宏进行元编程
Metaprogramming via macro
本文关键字:编程 更新时间:2023-10-16
我想做同样的事情,我们可以用C/c++预处理器做D的mixins。我想写一个函数来生成一个参数表。例如:
#define MK_FN_FOO(n,t) …
MK_FN_FOO(3,float)
/* it will expand into */
void foo(float x0, float x1, float x2) {
/* do something else here */
}
我有一些想法,但我面临一个问题。我必须做递归,我不知道怎么做这样的事情:
#define MK_FOO(n,t) void foo(MK_FOO_PLIST(n-1,t)) { }
#define MK_FOO_PLIST(n,t) t xn, MK_FOO_PLIST(n-1,t) /* how stop that?! */
boost库具有大量的元编程和其他所有预处理器库。可以使用他们的实用程序预处理器指令来做这种事情,这比自己做要容易得多,尽管仍然有点令人困惑:)
我建议你从这里开始:
http://www.boost.org/doc/libs/1_53_0/libs/preprocessor/doc/index.html http://www.boost.org/doc/libs/?view=category_Preprocessor编辑:这里是另一个关于它们的教程:提振。预处理器-教程
我已经检查了/boost/preprocessor/repetition/repeat.hpp
中的boost实现,对于您的示例,它将归结为这样的内容:
#define MK_FN_FOO_REPEAT_0(t)
#define MK_FN_FOO_REPEAT_1(t) MK_FN_FOO_REPEAT_0(t) t x0
#define MK_FN_FOO_REPEAT_2(t) MK_FN_FOO_REPEAT_1(t), t x1
#define MK_FN_FOO_REPEAT_3(t) MK_FN_FOO_REPEAT_2(t), t x2
#define MK_FN_FOO_REPEAT_4(t) MK_FN_FOO_REPEAT_3(t), t x3
// etc... boost does this up to 256
#define MK_FN_FOO(n, t) void foo(MK_FN_FOO_REPEAT_ ## n(t))
MK_FN_FOO(3, float) // will generate: void foo(float x0, float x1, float x2)
{
}
相关文章:
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 模板元编程:如何将参数包组合成新的参数包
- Qt Q串行端口未编程设备未关闭
- 模板元编程 - 尝试实现维度分析
- 我是编程新手
- C++编程从外部文本文件定义数组大小
- 了解算法的性能差异(如果以不同的编程语言实现)
- 使用 Gtkmm 以编程方式选择 Gtk::TextView 中的文本
- 如何将可变参数模板转换为多个单个模板?(C++竞争编程调试模板)
- 使用命名空间正确编程
- C++编程:运算符重载中的引用如何工作?
- Arduino 模块化编程与全局和设置
- C++ 运算符修改/元编程策略,用于不那么冗长的语法
- 在没有管理员权限的情况下,在 c++ 中以编程方式将程序添加到启动
- 如何以编程方式将音频从任何录制设备路由到任何播放设备
- 试图修复一个错误,该错误不会让我开始编程其余部分
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- Frank Luna 在他的书"使用 DirectX12 进行 3D 游戏编程"的介绍中盒子示例的问题
- 如何使用可变参数模板类使用模板元编程获得最大值