vard
vard

Reputation: 2302

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?

Upvotes: 2

Views: 338

Answers (3)

Anton Savin
Anton Savin

Reputation: 41331

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_;
};

Upvotes: 4

randomusername
randomusername

Reputation: 8105

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.

Upvotes: 2

galinette
galinette

Reputation: 9292

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.

Upvotes: -1

Related Questions