【问题标题】:How is std::vector<bool> declared/defined?std::vector<bool> 是如何声明/定义的?
【发布时间】:2014-11-12 01:47:00
【问题描述】:

在各种在线资源中,我读到std::vector&lt;bool&gt; 具有与其他类型的 std::vectors 完全不同的自定义行为。

具体来说,它压缩了向量,使得每个索引代表一个位,而不是标准的 bool 类型(32 位或不管它有多大)。

我的问题是,如何定义 std::vector 来实现这一点?
您可以覆盖模板类的现有行为,但仅针对特定模板参数吗? (布尔,在这种情况下)
这是否实现了无需定义整个派生类并使用继承覆盖/重新定义行为?

【问题讨论】:

  • 这称为专业化

标签: c++ oop templates vector std


【解决方案1】:

您能否覆盖模板类的现有行为,但仅限于特定模板参数?

是的。这被称为专业化,是模板元编程的基本构建块之一。

对于第一个模板参数为bool 的情况,

std::vector部分特化,如下所示:

namespace std {
    template<class T, class Alloc = std::allocator<T>>
    class vector {
        // normal vector stuff
    };

    template<class Alloc>
    class vector<bool, Alloc> {
        // special code for bools
    };
}

您也可以完全专门化一个类模板。例如:

struct Bar;

template<class T>
struct Foo {
     // standard stuff
};

template <>
struct Foo<Bar> {
     // special stuff in case T is Bar
};

这可以以许多有趣的方式使用。例如,您可以编写一个类型来检测另一个类型是否为std::vector

template<class T>
struct is_vector {
    static const bool value = false;
};

template<class T, class A>
struct is_vector<std::vector<T, A>> {
   static const bool value = true;
};

【讨论】:

  • 有趣...感谢您的详细回复。在您总结的向量专业化中,为 Alloc 参数提供默认值是否有任何目的?例如模板>
  • @Giffyguy 不,部分特化不能有默认参数
猜你喜欢
  • 2011-05-08
  • 2015-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-08
  • 2015-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多