File size: 2,306 Bytes
b27bfb3
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "cpp-variant-optional", "name": "Use std::variant, std::optional, and std::any for type-safe unions"}
{"type": "message", "message": {"role": "system", "content": "You are an expert C++ developer. You write clean, efficient, and idiomatic code."}}
{"type": "message", "message": {"role": "user", "content": "Use std::variant, std::optional, and std::any for type-safe unions"}}
{"type": "message", "message": {"role": "assistant", "content": "#include <variant>\n#include <optional>\n#include <any>\n#include <iostream>\n#include <string>\n#include <vector>\n\n// Variant as tagged union\nusing Value = std::variant<int, double, std::string>;\n\nvoid printValue(const Value& v) {\n    std::visit([](const auto& val) {\n        using T = std::decay_t<decltype(val)>;\n        if constexpr (std::is_same_v<T, int>) std::cout << \"int: \" << val;\n        else if constexpr (std::is_same_v<T, double>) std::cout << \"double: \" << val;\n        else if constexpr (std::is_same_v<T, std::string>) std::cout << \"string: \" << val;\n    }, v);\n    std::cout << \"\\n\";\n}\n\n// Optional\nstd::optional<int> findValue(const std::vector<int>& vec, int target) {\n    for (size_t i = 0; i < vec.size(); ++i) {\n        if (vec[i] == target) return i;\n    }\n    return std::nullopt;\n}\n\n// Any for type-erased storage\nvoid demonstrateAny() {\n    std::any a = 42;\n    std::cout << \"any: \" << std::any_cast<int>(a) << \"\\n\";\n\n    a = std::string(\"hello\");\n    std::cout << \"any: \" << std::any_cast<std::string>(a) << \"\\n\";\n\n    a = std::vector<int>{1, 2, 3};\n    auto& vec = std::any_cast<std::vector<int>&>(a);\n    for (int v : vec) std::cout << v << \" \";\n    std::cout << \"\\n\";\n}\n\nint main() {\n    // Variant\n    Value v1 = 42;\n    Value v2 = 3.14;\n    Value v3 = std::string(\"hello\");\n\n    printValue(v1);\n    printValue(v2);\n    printValue(v3);\n\n    // Get type\n    if (auto* p = std::get_if<int>(&v1)) {\n        std::cout << \"v1 is int: \" << *p << \"\\n\";\n    }\n\n    // Optional\n    std::vector<int> nums = {10, 20, 30, 40, 50};\n    if (auto pos = findValue(nums, 30)) {\n        std::cout << \"Found at index: \" << *pos << \"\\n\";\n    }\n\n    // Any\n    demonstrateAny();\n\n    return 0;\n}"}}