簡體   English   中英

c++ 模板參數推導

[英]c++ template argument deduce

Q1:

template  <typename  T> void print(const T &) {cout("INT &");}
template  <typename  T> void print( T  ) {cout("INT");}

int main() {
    int i = 10;
    print(i);
}

編譯器說“錯誤:重載 'print(int&)' 的調用不明確”

為什么?

“const T &”和“T”是一樣的嗎?

Q2:

template <typename T> void f( T){cout("F-T");};
template <typename T> void f( const T*){cout("F-T*");};
int main() {
    int ix = 43, *p=&ix;
    const int ci = 0, *p2 = &ci;
    f(p); // why result is "F-T"?
}

p 是指針,非 const 可以強制轉換為 const。

為什么 f(p) 選擇 f(T)?

對於問題 1:兩個重載都同樣“好”, T都推導出為int 在沒有“最佳”重載的情況下進行調用是錯誤的。 你得到同樣的

void print(const int &) { std::cout << "const int &"; }
void print(int) { std::cout << "int"; }

對於問題 2:第一個重載,推導Tint * ,比第二個重載更好,推導Tint

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM