example3_visiting_a_variant.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <iostream>
#include <variant>
#include <string>

struct Visitor {
    void operator()(int i) const { std::cout << "Int: " << i << std::endl; }
    void operator()(float f) const { std::cout << "Float: " << f << std::endl; }
    void operator()(const std::string& s) const { std::cout << "String: " << s << std::endl; }
};

int main() {
    std::variant<int, float, std::string> v = 3.14f;
    std::visit(Visitor{}, v);
    
    return 0;
}
Back to variant