I have a templated class that has a data member of type std::vector<T>, where T is also a parameter of my templated class.
In my template class I have quite some logic that does this:
T &value = m_vector[index];
This doesn’t seem to compile when T is a boolean, because the [] operator of std::vector does not return a bool-reference, but a different type.
Some alternatives (although I don’t like any of them):
- tell my users that they must not use bool as template parameter
- have a specialization of my class for bool (but this requires some code duplication)
Isn’t there a way to tell std::vector not to specialize for bool?
You simply cannot have templated code behave regularly for
Tequal toboolif your data is represented bystd::vector<bool>because this is not a container. As pointed out by @Mark Ransom, you could usestd::vector<char>instead, e.g. through a trait like thisand then use
typename vector_trait<T>::typewherever you currently usestd::vector<T>. The disadvantage here is that you need to use casts to convert fromchartobool.An alternative as suggested in your own answer is to write a wrapper with implicit conversion and constructor
and use
std::vector< wrapper<bool> >everywhere without ever having to cast. However, there are also disadvantages to this because standard conversion sequences containing realboolparameters behave differently than the user-defined conversions withwrapper<bool>(the compiler can at most use 1 user-defined conversion, and as many standard conversions as necessary). This means that template code with function overloading can subtly break. You could uncomment theexplicitkeywords in the code above but that introduces the verbosity again.