[英]Can't resolve Error: non-const lvalue reference to type 'bool' cannot bind to a temporary of type '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
,例如,當您的T
為bool
時,通過禁止它為您的矩陣 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.