Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...