首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 函數模板重載解析與最佳匹配規則

     編輯:關於C++

模板重載核心機制

函數模板重載本質是實例化特定模板,確定 T 型別,選擇匹配度最高者。關鍵在於理解實參型別如何映射至模板參數。

型別推導關鍵規則

  • 傳遞 &s(string 物件位址) → 實際匹配 string* t → 推導 T = string*
  • 非模板函數與模板函數匹配度相同時,優先選擇非模板函數
  • 模板宣告順序影響尋找,需前置宣告確保可見性

完整重載範例

/* 
 * cppprimer.cpp - 函數模板重載範例
 * Created on: 2013.11.28
 * Author: Caroline 
 * eclipse cdt, gcc 4.8.1
 */
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
using namespace std;

// 通用模板版本
template <typename T>
std::string debug_rep(const T &t) {
    std::ostringstream ret;
    ret << t;
    return ret.str();
}

// 指標版本
template <typename T>
std::string debug_rep(T *p) {
    std::ostringstream ret;
    ret << "pointer: " << p;
    if (p) ret << " " << debug_rep(*p);
    else ret << " null pointer";
    return ret.str();
}

// 非模板版本:string 專用
std::string debug_rep(const string &s) {
    return '"' + s + '"';
}

// char* 重載
std::string debug_rep(char *p) {
    std::cout << "plain ";
    return debug_rep(std::string(p));
}

// const char* 重載
std::string debug_rep(const char *p) {
    std::cout << "const ";
    return debug_rep(std::string(p));  // 呼叫通用模板
}

int main(void) {
    std::string s("hi");
    
    std::cout << debug_rep(s) << std::endl;      // "hi" - 非模板優先
    std::cout << debug_rep(&s) << std::endl;    // pointer: 0x... hi - 指標模板
    const std::string *sp = &s;
    std::cout << debug_rep(sp) << std::endl;    // pointer: 0x... hi - 指標模板
    std::cout << debug_rep("hello world") << std::endl; // const "hello world" - const char* 重載
    
    return 0;
}

輸出結果分析

"hi"
pointer: 0x22fec4 hi
pointer: 0x22fec4 hi
const "hello world"

匹配優先順序總結

  1. 非模板函數(完全匹配)
  2. 模板特化(template<>)
  3. 模板實例化(依參數推導匹配度)
  4. 隱式轉換(如 const char* → std::string)

設計重載組時,應確保非模板版本處理特殊情況,模板版本提供通用支援,避免模糊匹配導致編譯錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved