如何告诉自动推断向量<bool>元素的非引用类型
how to tell auto to deduce a non reference type for element of vector<bool>
这是代码:
int main()
{
std::vector<bool> b(5,false);
auto b0=b[0];
cout<<b0;
b[0]=true;
cout<<b0;
std::vector<int> i(5,false);
auto i0=i[0];
cout<<i0;
i[0]=true;
cout<<i0;
return 0;
}
0100
变量 b0 具有引用类型 (std::_Bit_reference(,而 i0 是普通整数。告诉 auto 推断一些非引用类型(例如 bool(的正确语法是什么?
你正在std::_Bit_reference
,因为std::vector
有一个"可能"节省空间的实现,用于bool
模板专用化(即std::vector<bool>
(。
正如cppreference所说,向量以位而不是字节存储值:
std::vector 节省空间的方式(以及它是否被优化(是实现定义的。一种可能的优化涉及合并向量元素,以便每个元素占用一个位而不是 sizeof(bool( 字节。
正如 templatetypedef 所说,auto
采取了它可以推断的第一件事,这恰好是一些用于从位中获取布尔值的花哨类型。
将类 std::vector::reference 公开为访问单个位的方法。特别是,此类的对象由运算符 [] 按值返回。
>operator bool() const;
>(until C++11)
>operator bool() const noexcept;
>(since C++11)
>Returns the value of the referenced bit.
它是隐式转换为布尔值 (AFAIK( 的,因此您不必担心将其传递给需要bool
参数的函数。
>auto
使用模板规则进行类型推断。你无法改变这一点。如果这不是你想要的,那么不要使用auto
,而是用手写出类型
即使remove_reference也无法删除引用:
#include <iostream>
#include <vector>
#include <typeinfo>
using namespace std;
int main()
{
std::vector<bool> b(5,false);
std::remove_reference< decltype(b[0])>::type b0=b[0];
cout<<typeid(b0).name()<< b0;
b[0]=true;
cout<<b0;
return 0;
}
St14_Bit_reference01
相关文章:
- 写入向量<向量<bool>>
- EASTL矢量<向量<int>>连续的
- 让bool方法返回其他整数
- 如何在 std::vector 中找到<bool>哪些索引是真的?
- Arduino-C++ bool 不会从 false 变为 true
- 为什么在这种情况下,bool 类型的输出等于 0?
- 显式 std::exception_ptr 转换为 bool 不存在.VS2010 错误?
- 错误:不能使用"显式"说明符声明 bool'
- 为什么 C++ 11 在 ios 类中添加了运算符 bool
- 从标准::字符串到标准::矢量<bool>的快速转换
- 为什么 bool 和 _Bool 如果它们在内存中占用 1 个字节,它们只能存储 0 或 1
- 通过 mpi 发送 c++ 标准::矢量<bool>
- 为什么使用Pool和Bool而不是int8_t或char
- 如何为地图< map<int,int> 、bool > 分配值?
- 为什么更改包含 psapi.h 的顺序会产生编译错误?(标识符 BOOL 未定义)
- 使用 bool 和 const char 重载的 C++ 函数会在没有警告的情况下产生歧义 (MSVC2012)
- 返回 bool 作为 CPP 中 bool 运算符 [] 中的值
- 如何告诉自动推断向量<bool>元素的非引用类型
- 当 Type = bool 时,运算符 bool() 与模板 Type() 运算符冲突
- 为什么"std::set::erase(const key_type&)"返回"size_type"而不是"bool"?