解決參數個數、類型不固定的函數封裝問題,遞歸展開參數包。
#include <iostream>
#include <array>
void showall() { return; } // 遞歸終止
template <typename R1, typename... Args>
void showall(R1 var, Args... args) {
std::cout << var << std::endl;
showall(args...); // 剩餘參數遞歸
}
int main() {
showall(1, 2, 3, 4, 5);
showall("gxjun", "dadw", "dasds");
showall(1.0, 2.0, 3.5);
return 0;
}
重載 operator() 的類/結構體,可像函數一樣調用,配合 std::bind 綁定成員函數。
#include <iostream>
#include <functional>
using namespace std;
template <typename R1, typename R2>
struct Calc {
void add(R1 a) { cout << a << endl; }
void add_1(R1 a, R1 b) { cout << a + b << endl; }
};
int main() {
Calc<int, int> calc;
auto fun = bind(&Calc<int,int>::add, &calc, placeholders::_1);
auto fun2 = bind(&Calc<int,int>::add_1, &calc, placeholders::_1, placeholders::_2);
fun(123); fun2(12, 24);
return 0;
}
簡化複雜類型聲明,統一函數指針調用接口。
// using 別名 using Func = int(*)(int, int, int, int); Func func = calc; // calc 為可變參數模板函數 func(1,2,3,4);
利用模板特化在編譯期完成遞歸計算,運行期直接取結果。
template <long N> struct Fib {
enum { res = Fib<N-1>::res + Fib<N-2>::res };
};
template <> struct Fib<1> { enum { res = 1L }; };
template <> struct Fib<0> { enum { res = 1L }; };
// 使用:Fib<45>::res 編譯期即得出結果
| 模式 | 代碼 | 特點 |
|---|---|---|
| 裸指針不釋放 | double* p = new double; | 內存洩漏 |
| 裸指針手動釋放 | delete p; | 易忘釋放/重複釋放 |
| auto_ptr (C++98) | auto_ptr<double> ps(p); | 所有權轉移,已棄用 |
| unique_ptr (C++11) | unique_ptr<double> ps(new double); | 獨占所有權,推薦使用 |
智能指針優勢:自動釋放、避免洩漏、異常安全、無運行期開銷。