如何告诉自动推断向量<bool>元素的非引用类型

how to tell auto to deduce a non reference type for element of vector<bool>

本文关键字:gt bool 元素 引用类型 何告诉 lt 向量      更新时间:2023-10-16

这是代码:

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