简体   繁体   中英

c++ avoid vector<bool> instantiation

I have some class template over 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. All is ok, but vector<bool> instantiation absolutely doesn't suitable for such purpose. I would like to have vector<char> or vector<uint8_t> instead of vector<bool> instantiations in my class. Also I cant use additional libraries like boost, standart library only.

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):

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 .

Use template specialization for the T=bool type. Then for all types except bool, vector is used.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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