2016-07-04 1 views
0

다음 코드는 예제 코드에서 boost :: type_traits를 사용하는 방법을 보여줍니다. 두 변수를 교환하는 두 가지 방법을 사용합니다. 두 변수가 정수 (int) 일 때 유형 유형이 true_type에 해당한다는 것을 쉽게 이해할 수 있습니다. 그러나 두 변수가 bool 유형 인 경우 더 이상 true_type으로 간주되지 않습니다. 왜 그런 일이 일어 났을까요? 감사.bool이 C++에서 boost :: true_type으로 간주되지 않는 이유는 무엇입니까?

#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 is a proxying iterator or not, and 
// uses optimal form accordingly: 
// 
namespace detail{ 

template <typename I> 
static void do_swap(I one, I 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, I 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 is both arguments are non-proxying iterators, 
    // and if both iterator the 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 
    // really just a check that it does 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; 
} 
+1

A 벡터 는 특수한 벡터입니다. 법선 벡터처럼 행동하지 않습니다. cppreference.com에서 확인할 수 있습니다. – NathanOliver

답변

1

있습니다 (주석으로) 코드에서이 해답을 가지고 :

참조는 두 인수가 아닌 프록시 반복자

되어있다

vector<bool> 때문에, 프록시 반복자있다 당신은 직접적으로 조금을 참조 할 수 없습니다. vector<bool>이 '요소를 개별 불린으로 저장 한 경우 (시스템에 따라 1-4 바이트/항목을 사용함) 반복기는 프록시를 사용하지 않을 수 있습니다. 대신 vector<bool>은 8 개의 항목/바이트를 저장하고 프록시 반복자를 사용합니다.

관련 문제