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)

使用conceptrequires明确模板参数要求。

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. 明确typenametemplate在依赖类型中的使用场景
相关推荐
也些宝9 小时前
Java单例模式:饿汉、懒汉、DCL三种实现及最佳实践
java
Nyarlathotep01139 小时前
SpringBoot Starter的用法以及原理
java·spring boot
wuwen59 小时前
WebFlux + Lettuce Reactive 中 SkyWalking 链路上下文丢失的修复实践
java
SimonKing9 小时前
GitHub 10万星的OpenCode,正在悄悄改变我们的工作流
java·后端·程序员
Seven9710 小时前
虚拟线程深度解析:轻量并发编程的未来趋势
java
雨中飘荡的记忆20 小时前
ElasticJob分布式调度从入门到实战
java·后端
考虑考虑1 天前
JDK25模块导入声明
java·后端·java ee
_小马快跑_1 天前
Java 的 8 大基本数据类型:为何是不可或缺的设计?
java
Re_zero1 天前
线上日志被清空?这段仅10行的 IO 代码里竟然藏着3个毒瘤
java·后端
洋洋技术笔记1 天前
Spring Boot条件注解详解
java·spring boot