簡體   English   中英

錯誤:無法將“bool&”類型的非常量左值引用綁定到“bool”類型的右值

[英]error: cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type ‘bool’

我正在創建自己的矩陣 Class。 當談到用於更改某個元素的值的“at” function 時,我有這個。

T & at(unsigned int raw, unsigned int col)
{
    return (_matrix.at(index(raw, col)));
}

知道

std::vector<T>  _matrix;

它適用於布爾值期望的所有類型。 我無法執行此操作。

matrix.at(1, 1) = true;

這很奇怪,因為我有與 std::vector "at" function 相同的實現,它適用於布爾值。

有任何想法嗎? 謝謝。

std::vector<bool>與所有其他std::vector特化不同。

它的.at成員 function 不返回對bool的引用,而是返回可以分配並轉換為bool的代理 object 。 正如您在return語句中所做的那樣,代理 object 和轉換后的bool (它是一個純右值)都不能綁定到bool&

您必須以特殊方式處理這種情況T = bool ,例如,當您的Tbool時,通過禁止它為您的矩陣 class 或使用std::vector<char>而不是std::vector<bool>

using U = std::conditional_t<std::is_same_v<T, bool>, char, T>;

std::vector<U>  _matrix;

然后在返回引用的任何地方返回U&而不是T& (這需要這種形式的#include<type_traits>和C++17,但可以適應C++11。)

或通過在bool周圍使用包裝器,例如

struct A {
    bool b;
};

您存儲在向量中而不是bool中,以便您仍然可以正確返回對bool成員的引用,

或者,如果您打算使用將std::vector<bool>與所有其他std::vector特化區分開來的打包存儲機制,則可以從.at方法返回代理 object 並基本上引入與std::vector為您的矩陣 class 提供,但是您需要注意矩陣 class 中各處的特殊情況:

decltype(auto) at(unsigned int raw, unsigned int col)
{
    return _matrix.at(index(raw, col));
}

(在這種情況下刪除 return 語句中的括號很重要,並且需要 C++14)或

std::vector<T>::reference at(unsigned int raw, unsigned int col)
{
    return _matrix.at(index(raw, col));
}

非常不幸的是std::vector<bool>在這種情況下是特殊的。 閱讀有關此問題的更多信息,例如在這個問題和 cppreference.com 頁面上std::vector<bool>

暫無
暫無

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

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