C++模板进阶技巧全解析

  1. 模板特化

模板特化允许为特定类型提供定制化的实现。

  • 全特化:为所有模板参数指定具体类型。
cpp 复制代码
template <typename T>
class MyClass {
public:
    void print() { std::[](https://en.cppreference.com/w/cpp/io/c) << "Generic type\n"; }
};

// 全特化版本
template <>
class MyClass<int> {
public:
    void print() { std::[](https://en.cppreference.com/w/cpp/io/c) << "Specialized for int\n"; }
};
  • 偏特化:为部分模板参数指定类型或约束。
cpp 复制代码
template <typename T1, typename T2>
class MyPair { /*...*/ };

// 偏特化:当两个类型相同时
template <typename T>
class MyPair<T, T> { /*...*/ };

2. 可变参数模板

允许模板接受任意数量的参数,使用...语法。

cpp 复制代码
template <typename... Args>
void printAll(Args... args) {
    (std::[](https://en.cppreference.com/w/cpp/io/c) << ... << args) << '\n'; // 折叠表达式(C++17)
}

// 递归展开示例
template <typename T>
void print(T t) {
    std::[](https://en.cppreference.com/w/cpp/io/c) << t << ' ';
}

template <typename T, typename... Args>
void print(T t, Args... args) {
    print(t);
    print(args...); // 递归调用
}

3. 模板元编程

在编译期执行计算,利用模板实例化机制。

cpp 复制代码
// 编译期计算阶乘
template <int N>
struct Factorial {
    static const int value = N * Factorial<N - 1>::value;
};

template <>
struct Factorial<0> {
    static const int value = 1;
};

// 使用
int main() {
    std::[](https://en.cppreference.com/w/cpp/io/c) << Factorial<5>::value; // 输出120
}

4. SFINAE

"替换失败不是错误",用于约束模板的有效性。

cpp 复制代码
#include <type_traits>

template <typename T>
auto foo(T t) -> std::enable_if_t<std::is_integral_v<T>, void> {
    std::[](https://en.cppreference.com/w/cpp/io/c) << "Integral type\n";
}

template <typename T>
auto foo(T t) -> std::enable_if_t<!std::is_integral_v<T>, void> {
    std::[](https://en.cppreference.com/w/cpp/io/c) << "Non-integral type\n";
}

5. 概念约束 (C++20)

使用concept和requires明确模板参数要求。

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;
}

6. 模板与完美转发

结合万能引用和std::forward实现参数高效传递。

cpp 复制代码
template <typename... Args>
void wrapper(Args&&... args) {
    target(std::forward<Args>(args)...);
}

注意事项

  1. 模板错误信息通常冗长复杂,需耐心分析
  2. 避免过度使用模板元编程导致编译时间过长
  3. 明确typename和template在依赖类型中的使用场景
相关推荐
lie..14 分钟前
30天从零开始学AI应用开发(Day 12):像产品一样稳:流式输出、报错重试、花钱控制
开发语言·人工智能·php
傻啦嘿哟18 分钟前
Python的默认参数把我坑惨了,原来写[]和写None的区别这么大
开发语言·python·机器学习
需要82626 分钟前
分布式事务:Seata AT/TCC/SAGA 的取舍与踩坑
java·spring boot·分布式·spring·spring cloud
晨小安39 分钟前
ThreadLocal及其内存泄漏问题深度解析
java·jvm·tomcat·哈希表
DeepAgent1 小时前
AI Agent 工程实践(49):一次真实优化——从 Agent v1 到 v2
开发语言·人工智能·agent
知识分享小能手1 小时前
C++ 学习教程,从入门到精通,C++对象和类 — 详细知识点总结(10)
开发语言·c++·学习
m0_587383001 小时前
深圳24小时自助健身房解决方案实战:从系统架构到部署指南
java·人工智能·spring boot·spring·系统架构·需求分析
郑州光合科技余经理1 小时前
同城电商系统:库存变更怎么同步到订单
java·开发语言·前端·后端·uni-app·php·ai编程
无序的浪2 小时前
测试博客-基于微服务的在线判题系统
java·spring cloud·docker·微服务·测试·在线判题
思茂信息2 小时前
CST软件BCI仿真模型及仿真案例
开发语言·单片机·嵌入式硬件·算法·emc