c++ - 重构模板函数中的常量表达式 if 语句
问题描述
我想重构以下代码:
enum Mode { None, Value1, Value2 }
template <Mode mode>
bool func() {
if (mode == None) {
helperNone();
return funcImplNone();
} else if (mode == Value1) {
helper1();
return funcImplValue1();
} else if (mode == Value2) {
helper2();
return funcImplValue2();
}
return true;
}
因为表达式
mode == None
在编译期间计算。而且这个代码不会导致代码膨胀(可执行文件中的代码重复)吗?
我正在考虑以下重构:
template<Mode>
bool func() {
return true;
}
template<>
bool func<None>() {
return true;
}
template<>
bool func<Value1>() {
helper1();
return funcImplValue2();
}
template<>
bool func<Value2>() {
helper2();
return funcImplValue2();
}
有没有其他标准的方法来重构它?我们是否保证编译器会优化该代码本身?重构后的代码是不是看起来更清晰了?
解决方案
在这里重构没有什么意义,因为无论如何它都在优化。例如下面的代码只产生一个对 funcImpl(); 的调用。
enum Mode { None, Other };
bool funcImpl();
template <Mode mode>
bool func() {
if (mode != None)
return funcImpl();
return true;
}
void test()
{
volatile auto a = func<None>();
a = func<Other>();
}
结果是
test():
sub rsp, 24
mov BYTE PTR [rsp+15], 1
call funcImpl()
mov BYTE PTR [rsp+15], al
add rsp, 24
ret
推荐阅读
- react-native - 尝试使用 expo 构建我的本机应用程序时出现“Android 资源编译失败”错误
- c++ - 以编程方式向 Chromium PasswordStore 添加新的密码形式
- powershell - 比较我的文件夹和他们的备份文件夹,看看我的备份解决方案是否有效
- azure-machine-learning-service - 如何在部署为 AKS Web 服务的 Azure 机器学习模型中包含运行状况检查终结点?
- javascript - 专门检测“加载脚本失败”错误事件
- python - 如何抓取没有唯一 ID 的字符串进行数据提取?
- python - 如果在 python 上具有特定条件,如何降低嵌套的复杂性
- java - Jmeter Beanshell 是否支持从 Kotlin jar 文件调用函数
- salt-stack - Saltstack:如何在 top.sls 中定义“小于版本的包......”
- java - 使用 JPA 时是否可以设置客户端连接属性?