Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

c++ - 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

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.

Is there a way how to get a reference of boolean variable from std::Vector? Or any different solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is there a way how to get a reference of boolean variable from std::Vector?

No.

Or any different solution?

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.

Or specialise A<bool> to use something other than vector<bool>.

Or use some other type (perhaps char, or a simple class wrapping a bool) instead of bool.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...