tinycodinglm / cpp /cpp-concepts-templates.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame
1.66 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 C++20 concepts for constrained templates and type traits

Assistant

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

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

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

template<Numeric T>
T square(T x) { return x * x; }

template<Container C>
void printContainer(const C& container) {
for (const auto& item : container) {
std::cout << item << " ";
}
std::cout << "\n";
}

template<typename T>
concept Printable = requires(std::ostream& os, const T& t) {
{ os << t } -> std::convertible_to<std::ostream&>;
};

template<Printable T>
void print(const T& value) {
std::cout << value << "\n";
}

// Constrained auto
template<Numeric T>
auto add(T a, T b) { return a + b; }

int main() {
std::cout << square(5) << "\n";
std::cout << square(3.14) << "\n";

markdown
std::vector<int> nums = {1, 2, 3, 4, 5};
std::vector<std::string> words = {"hello", "world"};

printContainer(nums);
printContainer(words);

print(42);
print("Hello");

return 0;

}