Why 'vector
Consider the following example:
#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); }
This code fails to compile with the following error:
dk2.cpp:29:28: error: no matching function for call to 'callIfToggled(const bool&, std::vector<bool>::reference, A&)'
The issue arises because 'std::vector
Vector Specialization for 'bool'
In the case of 'std::vector
'fixed_vector' and 'Boost Containers'
To mitigate this issue, you can use the following strategy:
Example Using 'fixed_vector':
template<typename t, typename... p> using fixed_vector = std::vector<typename foo<t>::type, p...>; int main() { fixed_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); }
Example Using 'Boost Containers':
#include <boost/container/vector.hpp> int main() { boost::container::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 above is the detailed content of Why Doesn't `std::vector::reference` Return a `bool` Reference?. For more information, please follow other related articles on the PHP Chinese website!