从 std::vector<bool> 获取布尔引用 [英] Getting a bool reference from std::vector<bool>

查看:24
本文介绍了从 std::vector<bool> 获取布尔引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于从 std::vector&lt;bool&gt; 获取布尔引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆