重载std :: bitset的移位运算符 [英] Overload the shift operators of std::bitset

查看:128
本文介绍了重载std :: bitset的移位运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用移位运算符对他们的实际位移位进行代替.这是我的预期行为:

I'd like to use the shift operators as doing a bit rotation instead of their actual bit shift. This is my expected behavior:

std::bitset<8> b8("1010"); // b8 = 00001010 
b8 <<= 5;                  // b8 = 01000001

因此,我尝试重载<<=运算符,并引用bitset定义,如下所示:

So I try and overloaded the <<= operator, referencing the bitset definition, as followed:

#include <iostream>
#include <bitset>

using namespace std;

template <size_t size>
bitset<size>& bitset<size>::operator<< (size_t pos) noexcept { // an error at here

}

关键字operator出现错误:

'operator<<'的脱机定义与'bitset< _Size>'

Out-of-line definition of 'operator<<' does not match any declaration in 'bitset<_Size>'

我该如何解决?我的环境是:

How can I fix it? My env. is:

  • Xcode:版本9.1(9B55)
  • LLVM(llvm-g++ -v):Apple LLVM版本9.0.0(clang-900.0.38)
  • Xcode : Version 9.1 (9B55)
  • LLVM(llvm-g++ -v) : Apple LLVM version 9.0.0 (clang-900.0.38)

推荐答案

std::bitset::operator<<=是模板类std::bitset的成员函数.您不能重新定义此运算符.而且您甚至无法将其隐藏起来:

std::bitset::operator<<= is a member function of the template class std::bitset. You cannot redefine this operator. And you cannot even hide it with another:

template <std::size_t size>
std::bitset<size>& operator<<=(std::bitset<size>& bitset, std::size_t count) noexcept {
    // ...
    return bitset;
}

由于您编写b8 <<= 5时,此代码可编译,但无法实现任何操作,因为在考虑您的自由功能之前,无限定ID的查找会找到std::bitset::operator<<=.

This compiles but achieves nothing since when you write b8 <<= 5, unqualified-id lookup finds std::bitset::operator<<= before considering your free function.

您应该使用其他运算符,定义rotate函数或定义包装旋转类:

You should use another operator, define a rotate function, or define a wrapper rotate class:

struct rotate
{
    rotate(std::size_t n) : value(n) {}
    std::size_t value;
};


template <std::size_t size>
std::bitset<size>& operator<<=(std::bitset<size>& bitset, rotate r) noexcept {
    bitset = bitset << r.value | bitset >> (size-r.value);
    return bitset;
}

用法:

std::bitset<8> b8("1010"); // b8 = 00001010 
b8 <<= rotate(5);          // b8 = 01000001

在大肠杆菌上进行演示

这篇关于重载std :: bitset的移位运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆