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 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 can use boost::variant or boost::any.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -