C++模板元编程技术详解 C模板元编程技术详解模板元编程是在编译期执行计算的技术通过模板特化和递归实现复杂的类型操作和算法。这种技术可以生成高效的代码避免运行时开销。模板递归是元编程的基础技术通过递归实例化模板来实现编译期计算。#include#includetemplatestruct Factorial {static constexpr int value N * Factorial::value;};templatestruct Factorial0 {static constexpr int value 1;};void factorial_example() {std::cout 5! Factorial5::value \n;std::cout 10! Factorial10::value \n;constexpr int result Factorial7::value;std::cout 7! result \n;}类型特征允许在编译期查询和操作类型信息。templatestruct RemoveConst {using type T;};templatestruct RemoveConst {using type T;};templateusing RemoveConst_t typename RemoveConst::type;templatestruct IsPointer {static constexpr bool value false;};templatestruct IsPointer {static constexpr bool value true;};templateconstexpr bool IsPointer_v IsPointer::value;void type_traits_example() {static_assert(std::is_same_v, int);static_assert(IsPointer_v);static_assert(!IsPointer_v);std::cout Type traits work correctly\n;}SFINAESubstitution Failure Is Not An Error是模板元编程的核心技术允许根据类型特征选择不同的实现。templatetypename std::enable_if::value, T::typeprocess(T value) {std::cout Processing integer: value \n;return value * 2;}templatetypename std::enable_if::value, T::typeprocess(T value) {std::cout Processing float: value \n;return value * 1.5;}void sfinae_example() {process(42);process(3.14);}constexpr if是C17引入的特性简化了编译期条件判断。templateauto process_v2(T value) {if constexpr (std::is_integral_v) {std::cout Integer: value \n;return value * 2;} else if constexpr (std::is_floating_point_v) {std::cout Float: value \n;return value * 1.5;} else {std::cout Other type\n;return value;}}变参模板允许处理任意数量的模板参数是实现通用库的关键技术。templatevoid print(Args... args) {((std::cout args ), ...);std::cout \n;}templateT sum(T value) {return value;}templateT sum(T first, Args... rest) {return first sum(rest...);}void variadic_template_example() {print(1, 2.5, hello, c);std::cout Sum: sum(1, 2, 3, 4, 5) \n;}折叠表达式是C17引入的特性简化了变参模板的处理。templateauto sum_fold(Args... args) {return (args ...);}templatevoid print_fold(Args... args) {((std::cout args ), ...);std::cout \n;}templatebool all_true(Args... args) {return (args ...);}void fold_expression_example() {std::cout Sum: sum_fold(1, 2, 3, 4, 5) \n;print_fold(Hello, World, 123);std::cout All true: all_true(true, true, true) \n;std::cout All true: all_true(true, false, true) \n;}类型列表是元编程中的重要数据结构用于在编译期操作类型序列。templatestruct TypeList {};templatestruct Length;templatestruct Length {static constexpr size_t value sizeof...(Types);};templatestruct TypeAt;templatestruct TypeAt, 0 {using type Head;};templatestruct TypeAt, N {using type typename TypeAt, N - 1::type;};templateusing TypeAt_t typename TypeAt::type;void type_list_example() {using MyList TypeList;static_assert(Length::value 4);static_assert(std::is_same_v, int);static_assert(std::is_same_v, char);std::cout Type list operations work correctly\n;}编译期字符串处理可以实现强大的元编程功能。templatestruct ConstString {char data[N];constexpr ConstString(const char (str)[N]) {for (size_t i 0; i N; i) {data[i] str[i];}}constexpr size_t length() const {return N - 1;}};templatestruct StringHolder {static constexpr const char* value str.data;};编译期映射可以实现类型到值的映射。templatestruct Pair {using key Key;using value Value;};templatestruct Map {};templatestruct MapGet;templatestruct MapGet, Rest..., Key {using type Value;};templatestruct MapGet, Rest..., Key {using type typename MapGet, Key::type;};void compile_time_map() {using MyMap MapPair,Pair,Pair;static_assert(std::is_same_v::type, double);static_assert(std::is_same_v::type, float);std::cout Compile-time map works correctly\n;}模板元编程可以实现编译期排序算法。templatestruct IntList {};templatestruct Sort;templatestruct Sort {using type IntList;};templatestruct Sort {using type IntList;};templatestruct Sort {using type typename std::conditional(First Second),typename Sort::type,typename Sort::type::type;};编译期素数判断展示了元编程的计算能力。templatestruct IsPrimeHelper {static constexpr bool value (N % D ! 0) IsPrimeHelper::value;};templatestruct IsPrimeHelper {static constexpr bool value true;};templatestruct IsPrime {static constexpr bool value N 1 IsPrimeHelper::value;};void prime_check() {static_assert(IsPrime2::value);static_assert(IsPrime17::value);static_assert(!IsPrime4::value);static_assert(!IsPrime15::value);std::cout Prime checks passed\n;}编译期斐波那契数列计算。templatestruct Fibonacci {static constexpr int value Fibonacci::value Fibonacci::value;};templatestruct Fibonacci0 {static constexpr int value 0;};templatestruct Fibonacci1 {static constexpr int value 1;};void fibonacci_example() {std::cout Fib(10) Fibonacci10::value \n;std::cout Fib(15) Fibonacci15::value \n;}类型擦除技术使用模板元编程实现运行时多态。class Any {struct HolderBase {virtual ~HolderBase() default;virtual HolderBase* clone() const 0;};templatestruct Holder : HolderBase {T value;explicit Holder(const T v) : value(v) {}HolderBase* clone() const override {return new Holder(value);}};HolderBase* ptr_;public:Any() : ptr_(nullptr) {}templateAny(const T value) : ptr_(new Holder(value)) {}~Any() {delete ptr_;}Any(const Any other) : ptr_(other.ptr_ ? other.ptr_-clone() : nullptr) {}Any operator(const Any other) {if (this ! other) {delete ptr_;ptr_ other.ptr_ ? other.ptr_-clone() : nullptr;}return *this;}templateT* cast() {auto holder dynamic_cast*(ptr_);return holder ? holder-value : nullptr;}};void type_erasure_example() {Any a 42;Any b std::string(hello);if (int* p a.cast()) {std::cout Integer: *p \n;}if (std::string* p b.cast()) {std::cout String: *p \n;}}模板元编程是C中强大但复杂的技术。它可以生成高效的代码实现编译期计算和类型操作但也会增加编译时间和代码复杂度。合理使用模板元编程可以创建灵活且高性能的库。