1

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.

roulette01
  • 1,984
  • 2
  • 13
  • 26
  • 3
    `std::auto_ptr` has been deprecated since C++11, so it's definitely _not_ the solution here. – Etienne de Martel Jun 16 '22 at 03:34
  • @Martel yes sorry I misunderstood what auto_ptr did – roulette01 Jun 16 '22 at 03:36
  • An important consideration here is `flag` -- is its value known during pre-processing? (If not, when is its value determined?) – JaMiT Jun 16 '22 at 04:43
  • Your title says "static object" but your use of an `if` statement suggests that the initialization occurs inside a function. Could you clarify this? Either remove "static" from the title or mention in the body that the object is being declared at global scope and the `if` statement is just illustrating intended behavior. – JaMiT Jun 16 '22 at 04:47
  • @JaMiT `flag` is a boolean only known at runtime, I think. I suppose we could make it a template variable, but we haven't done that yet. Yeah, sorry for the "static" terminology. I had a hard time figuring out how to describe it in the title. I'll edit it to mention that it's declared at global scope – roulette01 Jun 16 '22 at 15:38
  • @roulette01 Since `flag` is not known until runtime, how do you delay initializing the global object until after `flag` is known? Globals (and many statics) are initialized before `main()` executes. – JaMiT Jun 16 '22 at 23:32
  • Are `type1_t` and `type2_t` related? If not, are you allowed/willing to make them related using polymorphism? – Ted Lyngmo Jun 21 '22 at 20:24

1 Answers1

2

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

Laney
  • 1,571
  • 9
  • 7