[英]Getting a bool reference from 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);
}
};
It's possible to do things like this: 可以执行以下操作:
A<int> a{1,2,3,4};
a(3) = 10;
But it stops working if somebody uses bool as a template parameter 但是如果有人使用bool作为模板参数,它将停止工作
A<bool> a{true, false, true};
std::cout << a(0) << std::endl; // not possible
if (a(1)) { /* something */ } // not possible
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<bool>
是std::vector<bool>
的专用版本( http://www.cplusplus.com/reference/vector/vector-bool/ ),不允许这样做。
Is there a way how to get a reference of boolean variable from std::Vector? 有没有一种方法如何从std :: Vector获取布尔变量的引用? Or any different solution? 还是其他解决方案?
You hit the curse of the fake-container specialization. 您遇到了假货专业化的诅咒。
That's an acknowledged design-error the standard still propagates, so you need to specialize your template to avoid the standard-specialization. 这是标准仍在传播的公认的设计错误,因此您需要对模板进行专业化处理,以避免标准专业化。
Use a std::vector<mybool>
with struct mybool{bool value;};
使用带有struct mybool{bool value;};
的std::vector<mybool>
struct mybool{bool value;};
or some such in your specialization (and curse the stubborn committee for not deprecating it fast and undoing their error by now). 或您所擅长的领域中的一些此类问题(并责骂顽固的委员会,因为他们没有迅速弃之不用,现在就消除了他们的错误)。
Alternatively, just return std::vector<T>::reference
instead of T&
. 另外,只需返回std::vector<T>::reference
而不是T&
。 (Abstain if possible, don't propagate that wart) (Don't forget proper cursing) (如果可能,请弃权,不要传播疣)(不要忘记适当的诅咒)
Is there a way how to get a reference of boolean variable from std::Vector? 有没有一种方法如何从std :: Vector获取布尔变量的引用?
No. 没有。
Or any different solution? 还是其他解决方案?
Return typename std::vector<T>::reference
instead of T&
. 返回typename std::vector<T>::reference
而不是T&
。 For bool
, it will return the vector's proxy type; 对于bool
,它将返回向量的代理类型。 for others, it will return a regular reference. 对于其他人,它将返回常规参考。
Or specialise A<bool>
to use something other than vector<bool>
. 或专门使用A<bool>
来使用vector<bool>
以外的其他东西。
Or use some other type (perhaps char
, or a simple class wrapping a bool
) instead of bool
. 或者使用其他类型(也许是char
或包装bool
的简单类)代替bool
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.