从STD :: BITSET ::操作员[]扣除模板
Template deduction from std::bitset::operator[]
该代码如何不编译?为什么不能将bs[1]
推入bool
?
是否有一种通用方法可以解决此问题?
#include <iostream>
#include <string>
#include <bitset>
using namespace std;
template<typename T> struct StringConverter{};
template<> struct StringConverter<bool>{
std::string operator()(const bool &i){ return i?"true":"false"; }
};
template<typename T> std::string to_string(const T &val){
return StringConverter<T>()(val);
}
int main(){
// this does not compile
std::bitset<10> bs;
std::cout << to_string(bs[0]) << std::endl;
// this does
const std::bitset<10> bs_const;
std::cout << to_string(bs_const[0]) << std::endl;
}
编译器错误:
main.cpp:12:12: error: type 'StringConverter<std::bitset<10>::reference>' does not provide a call operator
return StringConverter<T>()(val);
^~~~~~~~~~~~~~~~~~~~
main.cpp:18:18: note: in instantiation of function template specialization 'to_string<std::bitset<10>::reference>' requested here
std::cout << to_string(bs[0]) << std::endl;
^
1 error generated.
non-const bitset :: operator []返回代理对象而不是bool(必须这样做,因为该代理可用于更改位值)。const bittet :: operator []但是,只返回一个布尔(不是参考,只是一个普通的布尔),因此它与StringConverter [
如果您检查了operator[]
的声明,您会注意到它具有两个过载 - const
一个,它返回bool
,并在您的第二个示例中使用,而非const
则使用返回类型std::bitset::reference
的对象。
后者用于BIT字段修改,并且绝对不能是bool&
,因为它必须解决特定位。对于这些代理返回类型,您遇到的问题很常见(这是我应该提到的vector<bool>
)。
作为一种可能的解决方案,您可以使用std::bitset::reference
可转换为bool
的事实(并且无法转换为您可能用于StringConverter
专业的任何其他可能的类型)。
相关文章:
- 如何打印大于"无符号长长"的"std::bitset"的十进制值?
- 关于 std::bitset 构造函数的几个问题?
- 如何以滑动窗口方式从 std::bitset 读取位并将它们转换为 int?
- 在哪里可以找到 std::bitset 的数据成员?
- 对于std::bitset,是否有一个ffs()等价物
- OMNeT++ cPacket as std::bitset 以应用 Reed-Solomon 编码
- 将字符数组转换为 std::string 以传递到 std::bitset seg 错误
- std::bitset 哈希函数算法
- 与STD :: BITSET的工会成员的结构填充
- 为什么 MSVC 在实现 std::bitset::count 时不使用 __popcnt?
- 如何在数字大于类型 size_t 的最大数量时使用 std::bitset
- 从STD :: BITSET ::操作员[]扣除模板
- 重载 std::bitset 的移位运算符
- 在编译时初始化 c++ std::bitset
- 为什么 std::bitset 只支持整型数据类型?为什么不支持浮点数?
- g++ 内存不足为 std::bitset 分配
- 使用 std::bitset 时程序崩溃,但仅在使用 VC 2015 编译时崩溃
- 使用std :: bitset进行双重表示
- STD :: BITSET ::参考对象在STD :: BITSET ::操作员[]中创建的寿命
- 改变std :: bitset中一系列位值的最有效方法