Skip to content

Instantly share code, notes, and snippets.

@saxbophone
Created June 11, 2022 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saxbophone/5ccd39c99b950585e531da0991bdd204 to your computer and use it in GitHub Desktop.
Save saxbophone/5ccd39c99b950585e531da0991bdd204 to your computer and use it in GitHub Desktop.
Automatically tracks which member of the union was last set
template <typename T, typename E, E SYMBOL>
class Proxy {
public:
Proxy(T& value, E& which) : ref(value), which(which) {}
Proxy& operator=(const T& value) {
ref = value;
which = SYMBOL;
}
operator T() { return ref; }
protected:
T& ref;
E& which;
};
class Multi {
union {
int integer;
char letter;
double number;
} shared;
public:
enum Which {
INTEGER,
LETTER,
NUMBER,
} which;
Proxy<int, Which, INTEGER> integer{shared.integer, which};
Proxy<char, Which, LETTER> letter{shared.letter, which};
Proxy<double, Which, NUMBER> number{shared.number, which};
};
#include <iostream>
int main() {
Multi m;
m.integer = 42;
std::cout << m.which << std::endl;
m.letter = 'c';
std::cout << m.which << std::endl;
m.number = 42.3216;
std::cout << m.which << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment