In various online resources, I've read that std::vector<bool>
has custom behaviors that are completely different from other types of std::vectors.
Specifically, it condenses the vector such that each index represents a single bit, rather than the standard bool type (32-bits or however big it is).
My question is, how was std::vector defined to achieve this?
Can you override the existing behavior of a template class, but only for specific template parameters? (bool, in this case)
Is this achieved without the need to define an entire derived class and override/redefine the behavior using inheritance?
Can you override the existing behavior of a template class, but only for specific template parameters?
Yes. This is known as specialization , and is one of the fundamental building blocks of template metaprogramming.
std::vector
is partially specialized for the case where the first template parameter is bool
, something like this:
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
};
}
You can also fully specialize a class template. For instance:
struct Bar;
template<class T>
struct Foo {
// standard stuff
};
template <>
struct Foo<Bar> {
// special stuff in case T is Bar
};
This can be used in many interesting ways. For example, you can write a type that detects if another type is a 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;
};
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.