简体   繁体   English

避免向量 <bool> 实例

[英]c++ avoid vector<bool> instantiation

I have some class template over std::vector: 我在std :: vector上有一些类模板:

template<typename T>
class MyClass{
public:
    // public methods;
private:
    std::vector<T> buffer_;
    // private methods and members
};

This is simplified version of my class. 这是我班的简化版本。 Internal vector here used as a buffer for sorting, different IO operation, relying on its single memory piece implementation such as fstreams custom buffer and buffer size known on runtime only. 内部vector在这里用作排序,不同IO操作的缓冲区,这取决于其单个内存块的实现,例如fstreams自定义缓冲区和仅在运行时已知的缓冲区大小。 All is ok, but vector<bool> instantiation absolutely doesn't suitable for such purpose. 一切正常,但是vector<bool>实例化绝对不适合此类目的。 I would like to have vector<char> or vector<uint8_t> instead of vector<bool> instantiations in my class. 我想在类中使用vector<char>vector<uint8_t>而不是vector<bool>实例化。 Also I cant use additional libraries like boost, standart library only. 我也不能使用其他的库,例如boost,standart库。

Is there any workaround? 有什么解决方法吗?

Create a helper class to determine the value type for the vector (this code uses C++11 but can easily be rewritten using only C++98): 创建一个辅助类来确定向量的值类型(此代码使用C ++ 11,但仅使用C ++ 98即可轻松重写):

template<typename T>
struct VectorValueType {
    using type = T;
};

template<>
struct VectorValueType<bool> {
    using type = char;
};

template<typename T>
using VectorValueType_t = typename VectorValueType<T>::type;

template<typename T>
class MyClass{
private:
    std::vector<VectorValueType_t<T>> buffer_;
};

Use a wrapper subclass like so: 使用包装子类,如下所示:

template<typename T>
struct sub_vector: public vector<T> {};

template<>
struct sub_vector<bool>: public vector<char> {};

And then just use that instead of vector . 然后使用它代替vector

Use template specialization for the T=bool type. 将模板专用化用于T = bool类型。 Then for all types except bool, vector is used. 然后,对于所有类型(布尔除外),都将使用vector。

template <typename T>
class MyClass
{
private:
    std::vector<T> buffer_;
};

template <>
class MyClass<bool>
{
private:
    std::vector<char> buffer_;
};

You need to specialize every member function that you will add, too. 您还需要专门化将添加的每个成员函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM