从 std::vector<bool> 获取布尔引用

2022-01-19 00:00:00 boolean c++ stdvector

我知道这是一个坏习惯,但我想知道一些解决方法或解决这个问题的技巧.我有这样的课:

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::reference 而不是 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.

相关文章