Question

This is a macro, and thus I hate it, but it "Works" for what I want:

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

It needs to be compile time (constexpr would work in C++11, but I'm stuck in c++98).

Anyone have a better way (boost is ok).

Was it helpful?

Solution

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);
}

OTHER TIPS

This can be done with templates (the static member is out-of-class since C++03 does not support in-class initialization of static members):

#include <iostream>

template<typename T, T val, T shift>
struct signed_shift {
    static T const value;
};

template<typename T, T val, T shift>
T const signed_shift<T,val,shift>::value
    = ((shift) < 0 ? val >> -shift : val << shift);

int main()
{
    std::cout << signed_shift<int, 1, 3>::value << '\n';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top