I see this piece of code for implementing a C++ std::variant-like type. This class is used as the variant storage.
What does the buffer array stores?
alignas(Types...) unsigned char buffer[sizeof(LargestT)];
I'm still learning, but for my understanding, maybe wrong, it stores the current largest type of the template pack list.
#include <new> // for std::launder()
template<typename... Types>
class VariantStorage {
using LargestT = LargestType<Typelist<Types...>>;
// What stores the following buffer array?
alignas(Types...) unsigned char buffer[sizeof(LargestT)];
unsigned char discriminator = 0;
public:
unsigned char getDiscriminator() const {
return discriminator;
}
void setDiscriminator(unsigned char d) {
discriminator = d;
}
void* getRawBuffer() {
return buffer;
}
const void* getRawBuffer() const {
return buffer;
}
template<typename T>
T* getBufferAs() {
return std::launder(reinterpret_cast<T*>(buffer));
}
template<typename T>
T const* getBufferAs() const {
return std::launder(reinterpret_cast<T const*>(buffer));
}
};
Can please anybody explain me what is the purpose of that line of code?
sizeof(LargestT)is worked out a compile time before anything has been stored in the variant. Instead it creates an array largest to store any type that the variant can hold.unsigned chararray. That buffer is used as the backing storage of whichever type is currently being stored in the variant. (Which can be any of the types. I'm not sure what you mean by "current largest", there is only the current type, which has its ownsizeof.)