#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? :)
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.
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.
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>
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With