c++ - 为什么 std::swap 不适用于 std::bitset<n> 内容?

标签 c++ c++11 swap bitset

考虑这个单元测试:

std::bitset<8> temp( "11010100" );
reverseBitSet( temp );
CPPUNIT_ASSERT( temp == std::bitset<8>( "00101011" ) );

此实现有效:

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

虽然这个没有:

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

结果是“11011011”而不是“00101011”

为什么交换做错了?

最佳答案

这个:

std::swap( bitset[pos], bitset[_Count-pos-1] );

应该实际编译失败。 operator[]对于 std::bitset 不返回引用,它返回一个代理对象。该代理对象不是左值,因此它不能绑定(bind)到 std::swap 中的 T&。我假设它完全可以编译这一事实意味着您正在使用 MSVC,它具有允许将临时对象绑定(bind)到非 const 引用的扩展 - 此时您可能只是交换代理而不是代理实际指的是什么。


旁注:名称 _Count 由标准保留,任何其他以 _ 开头后跟大写字母的名称也是如此。

关于c++ - 为什么 std::swap 不适用于 std::bitset<n> 内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39350396/

相关文章:

未检查 C++ 返回语句

c++ - 使用什么类型的堆以及 c++ 中 std::priority_queue 的时间复杂度?

c++ - 等效于范围枚举的 "using namespace X"?

c++ - 是否可以在 C++11 中手动设置 istream 失败位

c - 反转从二进制文件读取的指针

c++ - 错误 C2664 : cannot convert 'IDWriteFactory2 **' to 'IUnknown **'

c++ - 从字母转换成单词

c++ - 使用 decltype() 声明函数签名

c++ - 交换堆栈上的两个值

c - C 中的快速排序——指针和内存