Reputation: 1535
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?
Upvotes: 4
Views: 2169
Reputation: 45654
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;};
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&
. (Abstain if possible, don't propagate that wart) (Don't forget proper cursing)
Upvotes: 9
Reputation: 254431
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
.
Upvotes: 12