c++ - Using a variable that was defined in an if statement before -
int main() { if(i = 0) { myclass1 = "example1"; } else { myclass2 = "example2"; } cout << << endl; }
i know way defining outside block if have not decided type a
before checking condition of i
?
if able use c++17 can use std::variant
or std::any
in case types haven't common base class. these classes type-safe containers or specified types. example std::variant
can following:
#include <iostream> #include <string> #include <variant> int main() { bool input = false; std::cin >> input; std::variant<int, long, double, std::string> myvariant; if(input) myvariant = "example1"; else myvariant = 3.14; std::visit([](auto&& arg) { std::cout << arg << std::endl; }, myvariant); }
instead of c++17 can use boost::variant
or boost::any
.
Comments
Post a Comment