2016-07-04 10 views
0

次のコードは、boost :: type_traitsの使用方法を示すためのコード例です。 2つの変数をスワップする2つの方法を使用します。 2つの変数が整数(int)の場合、型の特性はtrue_typeに対応することは容易に理解できます。しかし、2つの変数が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

「ベクター」は特別なベクターです。法線ベクトルのようには動作しません。あなたはcppreference.comでそれをチェックすることができます – NathanOliver

答えて

1

あなたは(コメントとして)あなたのコードであり、答えを持っている:

参照は、両方の引数が非プロキシイテレータ

されている

vector<bool>ので、プロキシイテレータを持っています直接的には言及することはできません。 vector<bool>が個々のブール値(システムに応じて1〜4バイト/エントリを取る)として '要素を格納している場合、イテレータはプロキシではない可能性があります。代わりに、vector<bool>は8エントリ/バイトを格納し、プロキシイテレータを使用します。

関連する問題