Why doesn't std :: swap work with std :: bitset <n> content?
Consider this unit test:
std::bitset<8> temp( "11010100" ); reverseBitSet( temp ); CPPUNIT_ASSERT( temp == std::bitset<8>( "00101011" ) ); This implementation works:
template<size_t _Count> static inline void reverseBitSet( std::bitset<_Count>& bitset ) { bool val; for ( size_t pos = 0; pos < _Count/2; ++pos ) { val = bitset[pos]; bitset[pos] = bitset[_Count-pos-1]; bitset[_Count-pos-1] = val; } } While this is not:
template<size_t _Count> static inline void reverseBitSet( std::bitset<_Count>& bitset ) { for ( size_t pos = 0; pos < _Count/2; ++pos ) { std::swap( bitset[pos], bitset[_Count-pos-1] ); } } The result is "11011011" instead of "00101011"
Why does a shift do it wrong?
+7
jpo38
source share1 answer
It:
std::swap( bitset[pos], bitset[_Count-pos-1] ); should not compile. operator[] for std::bitset does not return a link, it returns a proxy object. This proxy object is not an lvalue value, so it cannot bind to T& in std::swap . I assume that it generally compiles that you are using MSVC, which has an extension that allows you to bind temporary links to const links - at this point you are probably just changing the proxies, and not what the proxies actually refer to.
Side note: the name _Count reserved by the standard, like any other name that begins with _ , followed by a capital letter.
+8
Barry
source share