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

Advanced C++ templates: SFINAE, CRTP, variadic templates, and type traits

Assistant

#include <iostream>
#include <type_traits>
#include <vector>
#include <string>

// SFINAE
template<typename T>
auto print(T x) -> std::enable_if_t<std::is_integral_v<T>> {
std::cout << "Integer: " << x << "\n";
}

template<typename T>
auto print(T x) -> std::enable_if_t<std::is_floating_point_v<T>> {
std::cout << "Float: " << x << "\n";
}

// CRTP
template<typename Derived>
class Counter {
static int count;
public:
Counter() { ++count; }
static int getCount() { return count; }
};

template<typename Derived>
int Counter<Derived>::count = 0;

class Widget : public Counter<Widget> {};
class Button : public Counter<Button> {};

// Variadic templates
template<typename... Args>
void printAll(Args... args) {
((std::cout << args << " "), ...) << "\n";
}

template<typename T, typename... Args>
auto makeVector(Args&&... args) {
std::vector<T> result;
(result.push_back(T(std::forward<Args>(args))), ...);
return result;
}

// Type traits
template<typename T>
void analyze() {
std::cout << "Type: " << typeid(T).name() << "\n";
std::cout << "Size: " << sizeof(T) << "\n";
std::cout << "Trivially copyable: " << std::is_trivially_copyable_v<T> << "\n";
std::cout << "Standard layout: " << std::is_standard_layout_v<T> << "\n\n";
}

int main() {
print(42);
print(3.14);

markdown
std::cout << "Widget count: " << Widget::getCount() << "\n";
Widget w1, w2;
std::cout << "Widget count: " << Widget::getCount() << "\n";

printAll(1, "hello", 3.14, 'c');

auto nums = makeVector<int>(1, 2, 3, 4, 5);
for (int n : nums) std::cout << n << " ";
std::cout << "\n";

analyze<int>();
analyze<double>();
analyze<std::string>();

return 0;

}