School notes / Charles University / Advanced C++

Czech notes

Lecture 8

Download Markdown · Download PDF

Type any

da se udelat:

any x;
x = 1;
x = "hello";
if (x.has_value()){
    std::cout << any_cast<std::string>(x) << std::endl;
}

variant:

std::variant<int, std::string> v;
v = 1;
v = "hello";
visit(v, [](auto&& arg){
    std::cout << arg << std::endl;
});

slovo overload:

  • neni a ani klicove slovo ani nic takoveho
std::variant<int, float, std::string> ifs (3.14f);

visit( overload{
    [](int i){ std::cout << "int: " << i << std::endl; },
    [](float f){ std::cout << "float: " << f << std::endl; },
    [](const std::string& s){ std::cout << "string: " << s << std::endl; }
}, ifs);