【问题标题】:Why bool is not regarded as boost::true_type in C++?为什么 bool 在 C++ 中不被视为 boost::true_type?
【发布时间】:2016-07-04 17:02:00
【问题描述】:

以下代码来自一个示例代码,用于说明如何使用 boost::type_traits。它将使用两种方法来交换两个变量。很容易理解,当两个变量都是整数 (int) 时,它们的类型特征对应于 true_type。但是,当两个变量是 bool 类型时,它们不再被视为 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;
}

【问题讨论】:

  • A vector&lt;bool&gt; 是一个特殊的向量。它的行为不像法线向量。您可以在 cppreference.com 上查看

标签: c++ boost typetraits


【解决方案1】:

您的代码中已找到答案(作为评论):

看看这两个参数都是非代理迭代器

vector&lt;bool&gt; 有代理迭代器,因为你不能直接引用位。 如果vector&lt;bool&gt; 将其元素存储为单独的布尔值(每个条目占用 1-4 个字节,具体取决于系统),则迭代器可能是非代理的。但是,vector&lt;bool&gt; 存储 8 个条目/字节并使用代理迭代器。

【讨论】:

    猜你喜欢
    • 2020-07-28
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 2015-05-31
    • 2017-05-05
    • 1970-01-01
    相关资源
    最近更新 更多