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

查看:92
本文介绍了从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>是vector的专用版本( 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>::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<bool>以外的其他内容.

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天全站免登陆