c++ - 编译带时间符号的移位运算符

标签 c++ c++98

这是一个宏,因此我讨厌它,但它可以满足我的需求:

#define signed_shift(val,shift) ((shift) < 0 ? (val) >> -(shift) : (val) << (shift))

它需要是编译时(constexpr 可以在 C++11 中工作,但我被困在 C++98 中)。

任何人都有更好的方法(提升是可以的)。

最佳答案

template <int val, int shift>
struct signed_shift
{
    static const int result = (shift < 0) ? (val >> -shift) : (val << shift);
};

int main()
{
    BOOST_STATIC_ASSERT(signed_shift<4, 3>::result == 32);
    BOOST_STATIC_ASSERT(signed_shift<4, 0>::result == 4);
    BOOST_STATIC_ASSERT(signed_shift<4, -1>::result == 2);
}

关于c++ - 编译带时间符号的移位运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23366370/

相关文章:

c++ - 我可以允许从 Qt 的任何地方打开窗口吗?

c++ - shared_ptr 和 shared_array 为引用计数器分配内存

c++ - 重载的新运算符每次都为新对象返回 NULL 内存

c++ - C++98 中的 std::remove_if 用法

c++ - C++ 如何推导出正确的重载函数?

c++ - 使用 LLVM-Clang 隐式实例化私有(private) C++ 模板的链接器错误

c++ - SDL2 在 Windows 上没有控制台输出

c++ - 如何在 C++ 中的字符串之间使用 cin?

c++ - 尝试递增 std::map 迭代器时出现 SIGBUS

c++ - 由于签名差异而调用了错误的子类函数