File size: 2,210 Bytes
b27bfb3
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "cpp-concepts-realworld", "name": "Apply C++20 concepts for type-safe APIs and better error messages"}
{"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": "Apply C++20 concepts for type-safe APIs and better error messages"}}
{"type": "message", "message": {"role": "assistant", "content": "#include <concepts>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <concepts>\n\n// Concept definitions\ntemplate<typename T>\nconcept Hashable = requires(T t) {\n    { std::hash<T>{}(t) } -> std::convertible_to<std::size_t>;\n};\n\ntemplate<typename T>\nconcept Container = requires(T t) {\n    std::begin(t);\n    std::end(t);\n    t.size();\n};\n\ntemplate<typename T>\nconcept Sortable = requires(T t) {\n    std::sort(t.begin(), t.end());\n};\n\ntemplate<typename T>\nconcept Numeric = std::integral<T> || std::floating_point<T>;\n\n// Constrained function template\nvoid printSorted(Sortable auto& container) {\n    std::sort(container.begin(), container.end());\n    for (const auto& item : container) std::cout << item << \" \";\n    std::cout << \"\\n\";\n}\n\ntemplate<Numeric T>\nT clamp(T value, T low, T high) {\n    return std::max(low, std::min(value, high));\n}\n\n// Constrained class\ntemplate<Hashable K, typename V>\nclass HashMap {\n    std::vector<std::pair<K, V>> data;\npublic:\n    void insert(K key, V value) {\n        data.emplace_back(std::move(key), std::move(value));\n    }\n    V* find(const K& key) {\n        for (auto& [k, v] : data) {\n            if (k == key) return &v;\n        }\n        return nullptr;\n    }\n};\n\nint main() {\n    std::vector<int> nums = {5, 3, 1, 4, 2};\n    printSorted(nums);\n\n    std::vector<std::string> words = {\"cherry\", \"apple\", \"banana\"};\n    printSorted(words);\n\n    std::cout << clamp(15, 0, 10) << \"\\n\";\n\n    HashMap<std::string, int> map;\n    map.insert(\"hello\", 42);\n    if (auto* val = map.find(\"hello\")) {\n        std::cout << \"Found: \" << *val << \"\\n\";\n    }\n\n    return 0;\n}"}}