簡體   English   中英

為什么 auto 為 std::bitset::operator [] 推導出引用對象而不是 bool

[英]Why auto deduces a reference object instead of bool for std::bitset::operator []

我有以下代碼

std::bitset<32> bs{21};
auto ref_obj = bs[0];
auto &another_ref = bs[0];
bool bool_obj = bs[0];

ref_obj的類型不是bool 但是another_refref_obj具有相同的類型。 std::bitset::operator[]http://en.cppreference.com/w/cpp/utility/bitset/operator_at列出了 3 個重載

但我想不通為什么會這樣。

根據 C++11 標准,如果您的 bitset 不是const (而您的不是),則返回引用類型:

§20.6.2 位集操作:

constexpr bool operator[](size_t pos) const; // for b[i];
reference operator[](size_t pos); // for b[i];

C++ 中的最小可尋址類型是一個字節,大概是至少 8 位[intro.memory/1] 因此,無法返回對單個(小於 1 個字節)的引用。 因此,當您需要對此進行引用時,會返回一個執行一些黑魔法的代理。

您的對象不是const ,因此假設您可能希望通過[]運算符修改元素。 您可以將其轉換為const引用並訪問const限定成員重載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM