Why bool is not regarded as boost::true_type in C++? -
the following codes come example code illustrate how use boost::type_traits. use 2 methods swap 2 variables. easy understand when 2 variables integer (int) type traits correspond true_type. however, when 2 variables bool type not regarded true_type more. why happen? thanks.
#include <iostream> #include <typeinfo> #include <algorithm> #include <iterator> #include <vector> #include <memory> #include <boost/test/included/prg_exec_monitor.hpp> #include <boost/type_traits.hpp> using std::cout; using std::endl; using std::cin; namespace opt{ // // iter_swap: // tests whether iterator proxying iterator or not, , // uses optimal form accordingly: // namespace detail{ template <typename i> static void do_swap(i one, two, const boost::false_type&) { typedef typename std::iterator_traits<i>::value_type v_t; v_t v = *one; *one = *two; *two = v; } template <typename i> static void do_swap(i one, two, const boost::true_type&) { using std::swap; swap(*one, *two); } } template <typename i1, typename i2> inline void iter_swap(i1 one, i2 two) { // // see both arguments non-proxying iterators, // , if both iterator same type: // typedef typename std::iterator_traits<i1>::reference r1_t; typedef typename std::iterator_traits<i2>::reference r2_t; typedef boost::integral_constant<bool, ::boost::is_reference<r1_t>::value && ::boost::is_reference<r2_t>::value && ::boost::is_same<r1_t, r2_t>::value> truth_type; detail::do_swap(one, two, truth_type()); } }; // namespace opt int cpp_main(int argc, char* argv[]) { // // testing iter_swap // check in fact compile... std::vector<int> v1; v1.push_back(0); v1.push_back(1); std::vector<bool> v2; v2.push_back(0); v2.push_back(1); opt::iter_swap(v1.begin(), v1.begin()+1); opt::iter_swap(v2.begin(), v2.begin()+1); return 0; }
you've got answer there in code (as comment):
see both arguments non-proxying iterators
vector<bool>
has proxy iterators, because can't refer directly bit. if vector<bool>
stored its' elements individual booleans (taking 1-4 bytes/entry, depending on system), iterators non-proxying. instead, vector<bool>
stores 8 entries/byte , uses proxy iterators.
Comments
Post a Comment