tinycodinglm / cpp /cpp-concepts-realworld.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
2.21 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

Apply C++20 concepts for type-safe APIs and better error messages

Assistant

#include <concepts>
#include <iostream>
#include <vector>
#include <string>
#include <concepts>

// Concept definitions
template<typename T>
concept Hashable = requires(T t) {
{ std::hash<T>{}(t) } -> std::convertible_to<std::size_t>;
};

template<typename T>
concept Container = requires(T t) {
std::begin(t);
std::end(t);
t.size();
};

template<typename T>
concept Sortable = requires(T t) {
std::sort(t.begin(), t.end());
};

template<typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;

// Constrained function template
void printSorted(Sortable auto& container) {
std::sort(container.begin(), container.end());
for (const auto& item : container) std::cout << item << " ";
std::cout << "\n";
}

template<Numeric T>
T clamp(T value, T low, T high) {
return std::max(low, std::min(value, high));
}

// Constrained class
template<Hashable K, typename V>
class HashMap {
std::vector<std::pair<K, V>> data;
public:
void insert(K key, V value) {
data.emplace_back(std::move(key), std::move(value));
}
V* find(const K& key) {
for (auto& [k, v] : data) {
if (k == key) return &v;
}
return nullptr;
}
};

int main() {
std::vector<int> nums = {5, 3, 1, 4, 2};
printSorted(nums);

markdown
std::vector<std::string> words = {"cherry", "apple", "banana"};
printSorted(words);

std::cout << clamp(15, 0, 10) << "\n";

HashMap<std::string, int> map;
map.insert("hello", 42);
if (auto* val = map.find("hello")) {
    std::cout << "Found: " << *val << "\n";
}

return 0;

}