tinycodinglm / cpp /cpp20-002.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame
2.11 kB
opencode trace
System You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing c...

You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies.

User

Explain C++20 concepts with practical examples

Assistant

C++20 Concepts:

Basic Concept:

cpp
template<typename T>
concept Addable = requires(T a, T b) {
    { a + b } -> std::convertible_to<T>;
};

template<Addable T>
T add(T a, T b) { return a + b; }

Compound Requirements:

cpp
template<typename T>
concept Sortable = requires(T container) {
    { container.begin() } -> std::input_iterator;
    { container.end() } -> std::sentinel_for<decltype(container.begin())>;
    { *container.begin() } -> std::totally_ordered;
};

Nested Requirements:

cpp
template<typename T>
concept Numeric = std::is_arithmetic_v<T>;

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

Concept Composition:

cpp
template<typename T>
concept Hashable = std::equality_comparable<T> && requires(T a) {
    { std::hash<T>{}(a) } -> std::convertible_to<size_t>;
};

If-Constexpr with Concepts:

cpp
template<typename T>
auto process(T val) {
    if constexpr (std::integral<T>) {
        return val * 2;
    } else if constexpr (std::floating_point<T>) {
        return val * 2.0;
    } else {
        return val;
    }
}

Abbreviated Function Templates:

cpp
// C++20: auto parameter
void print(std::integral auto val) {
    std::cout << val;
}

// Equivalent to:
template<std::integral T>
void print(T val) {
    std::cout << val;
}