Getting a bool reference from std::vectorlt;boolgt;(从 std::vectorlt;boolgt; 获取布尔引用)
问题描述
我知道这是一个坏习惯,但我想知道一些解决方法或解决这个问题的技巧.我有这样的课:
I know it's a bad habit, but I'd like to know some workaround or hack for this problem. I have a class like this:
template <class T>
class A : std::vector<T> {
T& operator()(int index) { // returns a _reference_ to an object
return this->operator[](index);
}
};
可以这样做:
A<int> a{1,2,3,4};
a(3) = 10;
但如果有人使用 bool 作为模板参数,它就会停止工作
But it stops working if somebody uses bool as a template parameter
A<bool> a{true, false, true};
std::cout << a(0) << std::endl; // not possible
if (a(1)) { /* something */ } // not possible
std::vector<bool>
是矢量的特殊版本 (http://www.cplusplus.com/reference/vector/vector-bool/) 不允许这样的事情.
std::vector<bool>
is a specialized version of vector (http://www.cplusplus.com/reference/vector/vector-bool/) which doesn't allow such things.
有没有办法从 std::Vector 获取布尔变量的引用?或者有什么不同的解决方案?
Is there a way how to get a reference of boolean variable from std::Vector? Or any different solution?
推荐答案
有没有办法从 std::Vector 获取布尔变量的引用?
Is there a way how to get a reference of boolean variable from std::Vector?
没有.
或者任何不同的解决方案?
Or any different solution?
返回 typename std::vector
而不是 T&
.对于bool
,它将返回向量的代理类型;对于其他人,它将返回一个常规引用.
Return typename std::vector<T>::reference
instead of T&
. For bool
, it will return the vector's proxy type; for others, it will return a regular reference.
或者专门化 A<bool>
以使用 vector
Or specialise A<bool>
to use something other than vector<bool>
.
或者使用其他类型(可能是 char
,或者包装 bool
的简单类)而不是 bool
.
Or use some other type (perhaps char
, or a simple class wrapping a bool
) instead of bool
.
这篇关于从 std::vector<bool> 获取布尔引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 std::vector<bool> 获取布尔引用


- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01