我想在复杂系统中使用代码部分,它与以下内容等效:
static constexpr int abits = 13;
static constexpr int bbits = 10;
...
int atob(int a) {
if ( abits == bbits ) return a;
else if ( abits > bbits ) return a >> (abits-bbits);
else return a << (bbits-abits);
}
Run Code Online (Sandbox Code Playgroud)
abits并且bbits可能会随着时间而改变(当然是在编译时).即使在调试模式下,最终代码中始终只编译一行.但是,我收到一个关于按负值移动的警告信息.
我使用GCC 7.3.0,并且不想避免负移位值上的所有警告.我想摆脱没有使用的代码的警告.但是,我没有找到它的开关.
constexpr if如果你的条件是a,你可以在编译时使用分支constexpr.
static constexpr int abits = 13;
static constexpr int bbits = 10;
int atob(int a) {
if constexpr ( abits == bbits ) return a;
else if constexpr ( abits > bbits ) return a >> (abits-bbits);
else return a << (bbits-abits);
}
Run Code Online (Sandbox Code Playgroud)
constexpr if是一个c ++ 17功能,可以在带有-std=c++17标志的gcc 7.3.0上找到.
编辑:一个c ++ 14解决方案可以使用std::enable_if.诀窍是为这三种情况提供过载,并且只启用适用的情况.
static constexpr int abits = 13;
static constexpr int bbits = 10;
#include <type_traits>
template<int I>
std::enable_if_t<I == 0, int>
atob_impl(int a) {
return a;
}
template<int I>
std::enable_if_t<(I > 0), int>
atob_impl(int a) {
return a >> (abits-bbits);
}
template<int I>
std::enable_if_t<(I < 0), int>
atob_impl(int a) {
return a << (bbits-abits);
}
int atob(int a) {
return atob_impl<abits - bbits>(a);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61 次 |
| 最近记录: |