c++ - 字符串化模板数字参数
问题描述
我有以下代码:
template<int maxRegNum> void f(MuliInstr instr);
template<> void f<0>(MuliInstr instr)
{
if (instr.regA == 0) asm volatile ("mov r4, r0");
}
template<int maxRegNum> void f(MuliInstr instr)
{
if (instr.regA == maxRegNum) asm volatile ("mov r4, r" ???);
f<maxRegNum - 1>(instr);
}
这 ???是代码中我想对 maxRegNum 进行字符串化的占位符,这是否可以使用 C++11 实现?C-预处理器解决方案也可以:-)
如果我需要从 30 个寄存器中做出选择,我想实现将其用作代码生成器,避免重复编写此汇编程序移动指令 30 次,例如
感谢您对这个问题的任何提示。
亲切的问候,史蒂夫
编辑:我想实现以下目标:
当我写 f<31>(instr); 在代码的某个地方,我想要这些行
if (instr.regA == 31) asm volatile ("mov r4, r31");
if (instr.regA == 30) asm volatile ("mov r4, r30");
if (instr.regA == 29) asm volatile ("mov r4, r29");
...
if (instr.regA == 0) asm volatile ("mov r4, r0");
放入编译结果
解决方案
不幸的是,您可能需要给出一个字符串文字asm
,而您无法使用模板构建它。
不过,您可以使用BOOST_PP_REPEAT_FROM_TO
宏轻松完成此操作:
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#define F_DEFINITION(_, maxRegNum, __) \
template<> void f<maxRegNum>(MuliInstr instr) { \
if (instr.regA == maxRegNum) asm volatile ("mov r4, r" #maxRegNum); \
f<maxRegNum - 1>(instr); \
}
BOOST_PP_REPEAT_FROM_TO(1, 30, F_DEFINITION, _)
如果没有 boost,你仍然可以通过使用宏来避免一些重复。regA
如果您是整数成员,这应该是等效的代码:
template<int maxRegNum> void f(MuliInstr instr) {
static_assert(maxRegNum <= 31, "maxRegNum > 31 not supported");
switch (instr.regA) {
#define F_CASE(n) \
case n: \
if (maxRegNum >= n) asm volatile ( "mov r4, r" #n ); \
break
#define F_CASE_8(a, b, c, d, e, f, g, h) F_CASE(a); F_CASE(b); F_CASE(c); F_CASE(d); F_CASE(e); F_CASE(f); F_CASE(g); F_CASE(h)
F_CASE_8(0, 1, 2, 3, 4, 5, 6, 7);
F_CASE_8(8, 9, 10, 11, 12, 13, 14, 15);
F_CASE_8(16, 17, 18, 19, 20, 21, 22, 23);
F_CASE_8(24, 25, 26, 27, 28, 29, 30, 31);
}
}
推荐阅读
- xml - 使用命名空间转换 XML 属性的 ITS 规则
- c# - 我有 2 个相同类型的武器槽,但是当我点击武器类型的物品时,只有 1 个槽被占用
- ruby-on-rails - 从 react 前端 react-on-rails 中的 rails 服务访问数据
- java - OPENJPA 2.4.3 显然在互联网上寻找持久性命名空间
- reactjs - 除非在 React 中单击两次搜索,否则查询字符串不会添加到 api
- python - 在 MLP 的情况下,张量流如何使用填充和遮罩层?
- testing - 在赛普拉斯中,如何找到具有相同 ID 的选择并获取长度?
- three.js - 带有 WebGLRenderer 的 CSS2DRenderer 不工作
- android - Android 房间数据库 - 不确定如何将 Cursor 转换为此方法的返回类型
- azure - Azure DNS 区域,www 响应 404