I want to do something like the following
if (flag) {
type1_t object = .....
} else {
type2_t object = .....
}
// do the same thing with object
type1_t and type2_t are custom classes. The problem with the above snippet is object remains local to each if else clause, but I can't define it above the if-else because the type is dependent on flag.
Late edit: It seems I can't use C++17 features in this codebase I'm working with so the std::variant idea won't work.
you can use
std::varianthere. Something likeNotice the usage of
std::monostate. That's becausestd::variant's default constructor uses the first alternative's default constructor.std::monostateis here to avoid that.Besides,
std::auto_ptris deprecated long time ago.std::unique_ptris much better