I program microcontrollers in my day job, so I'm weary of using
dynamic memory allocation. I avoid it wherever possible.
Currently I have an "interface class" [...]
class IRS232 {
[...] I have two classes that derive from IRS232, like this:
class RS232_Chunked : public IRS232 { . . . };
class RS232_Instant : public IRS232 { . . . };
[...] So I can do the following:
std::variant<std::nullopt_t,RS232_Chunked,RS232_Instant>
g_coms( std::in_place_index<0u>, std::nullopt );
IRS232 *g_pcoms = nullptr;
void Initialise_Comms(bool const chunked = false) {
if ( chunked ) {
g_coms.emplace<1u>();
g_pcoms = &std::get<1u>(g_coms);
[...]
In order to simply this, I think that the "std::variant" class should
have a method called "common_base", which could be used as follows:
This is just std::visit. Here's the "very simple" version using the Null Object pattern (i.e., creating a new dummy subclass of IRS232 to represent "no connection"):
And here's the "less simple" version:
There are other ways to do it too, but std::visit seems like the simplest — and it's already present in C++17.
HTH,
Arthur