导航菜单

模板编程

C++ / 模板编程

64%
函数模板基础

模板函数定义

使用模板实现通用的函数功能。

// 基本函数模板
template<typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}

// 多类型参数模板
template<typename T, typename U>
auto add(T a, U b) -> decltype(a + b) {
    return a + b;
}

// 带约束的函数模板(C++20)
template<typename T>
requires std::is_arithmetic_v<T>
T square(T x) {
    return x * x;
}

int main() {
    // 使用函数模板
    cout << max(10, 20) << endl;        // int类型
    cout << max(3.14, 2.72) << endl;    // double类型
    cout << max("hello", "world") << endl; // string类型
    
    // 多类型参数
    cout << add(5, 3.14) << endl;       // int + double
    
    // 带约束的模板
    cout << square(5) << endl;          // 整数
    cout << square(3.14) << endl;       // 浮点数
    // square("hello");                 // 编译错误:不满足约束
}