Reputation: 2472
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.
Upvotes: 1
Views: 103
Reputation: 1649
you can use std::variant
here. Something like
std::variant<std::monostate, type1_t, type2_t> object;
if (flag) { ... } else { ... }
Notice the usage of std::monostate
. That's because std::variant
's default constructor uses the first alternative's default constructor. std::monostate
is here to avoid that.
Besides, std::auto_ptr
is deprecated long time ago. std::unique_ptr
is much better
Upvotes: 2