tinycodinglm / cpp /cpp-variant-optional.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame
2.31 kB
opencode trace
System You are an expert C++ developer. You write clean, efficient, and idiomatic code.

You are an expert C++ developer. You write clean, efficient, and idiomatic code.

User

Use std::variant, std::optional, and std::any for type-safe unions

Assistant

#include <variant>
#include <optional>
#include <any>
#include <iostream>
#include <string>
#include <vector>

// Variant as tagged union
using Value = std::variant<int, double, std::string>;

void printValue(const Value& v) {
std::visit([](const auto& val) {
using T = std::decay_t<decltype(val)>;
if constexpr (std::is_same_v<T, int>) std::cout << "int: " << val;
else if constexpr (std::is_same_v<T, double>) std::cout << "double: " << val;
else if constexpr (std::is_same_v<T, std::string>) std::cout << "string: " << val;
}, v);
std::cout << "\n";
}

// Optional
std::optional<int> findValue(const std::vector<int>& vec, int target) {
for (size_t i = 0; i < vec.size(); ++i) {
if (vec[i] == target) return i;
}
return std::nullopt;
}

// Any for type-erased storage
void demonstrateAny() {
std::any a = 42;
std::cout << "any: " << std::any_cast<int>(a) << "\n";

markdown
a = std::string("hello");
std::cout << "any: " << std::any_cast<std::string>(a) << "\n";

a = std::vector<int>{1, 2, 3};
auto& vec = std::any_cast<std::vector<int>&>(a);
for (int v : vec) std::cout << v << " ";
std::cout << "\n";

}

int main() {
// Variant
Value v1 = 42;
Value v2 = 3.14;
Value v3 = std::string("hello");

markdown
printValue(v1);
printValue(v2);
printValue(v3);

// Get type
if (auto* p = std::get_if<int>(&v1)) {
    std::cout << "v1 is int: " << *p << "\n";
}

// Optional
std::vector<int> nums = {10, 20, 30, 40, 50};
if (auto pos = findValue(nums, 30)) {
    std::cout << "Found at index: " << *pos << "\n";
}

// Any
demonstrateAny();

return 0;

}