Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why vector<bool>::reference doesn't return reference to bool?

#include <vector>  struct A {     void foo(){} };  template< typename T > void callIfToggled( bool v1, bool &v2, T & t ) {     if ( v1 != v2 )     {         v2 = v1;         t.foo();     } }  int main() {     std::vector< bool > v= { false, true, false };      const bool f = false;     A a;      callIfToggled( f, v[0], a );     callIfToggled( f, v[1], a );     callIfToggled( f, v[2], a ); } 

The compilation of the example above produces next error :

dk2.cpp: In function 'int main()': dk2.cpp:29:28: error: no matching function for call to 'callIfToggled(const bool&, std::vector<bool>::reference, A&)' dk2.cpp:29:28: note: candidate is: dk2.cpp:13:6: note: template<class T> void callIfToggled(bool, bool&, T&) 

I compiled using g++ (version 4.6.1) like this :

g++ -O3 -std=c++0x -Wall -Wextra -pedantic dk2.cpp 

The question is why this happens? Is vector<bool>::reference not bool&? Or is it a compiler's bug?
Or, am I trying something stupid? :)

like image 715
BЈовић Avatar asked Dec 06 '11 11:12

BЈовић


People also ask

What is vector bool in c++?

The vector<bool> class is a partial specialization of vector for elements of type bool . It has an allocator for the underlying type that's used by the specialization, which provides space optimization by storing one bool value per bit.

How do you declare a boolean in C++?

In C++, we use the keyword bool to declare this kind of variable. Let's take a look at an example: bool b1 = true; bool b2 = false; In C++, Boolean values declared true are assigned the value of 1, and false values are assigned 0.


2 Answers

Vector is specialized for bool.

It is considered a mistake of the std. Use vector<char> instead:

template<typename t> struct foo {   using type = t; }; template<> struct foo<bool> {   using type = char; };  template<typename t, typename... p> using fixed_vector = std::vector<typename foo<t>::type, p...>; 

Occasionally you may need references to a bool contained inside the vector. Unfortunately, using vector<char> can only give you references to chars. If you really need bool&, check out the Boost Containers library. It has an unspecialized version of vector<bool>.

like image 176
Pubby Avatar answered Sep 19 '22 21:09

Pubby


Your expectations are normal, but the problem is that std::vector<bool> has been a kind of experiment by the C++ commitee. It is actually a template specialization that stores the bool values tightly packed in memory: one bit per value.

And since you cannot have a reference to a bit, there's your problem.

like image 28
rodrigo Avatar answered Sep 18 '22 21:09

rodrigo