簡體   English   中英

模板函數專業化與重載

[英]Template function specialization vs. overloading

從一些關於模板專業化的幻燈片:

#include <iostream>

using namespace std;

template<class X> 
X& min(X& a, X& b)
{
    return a > b ? b : a;
}

int& min(int& a, int & b)
{
    // rewrite of the function in the case of int:
    cout << "int explicit function\n";
    return a > b ? b : a;
}

/* 
new syntax – the more appropriate way:
template<>
int& min<int>(int& a, int& b)
{
    cout << "int explicit function\n";
    return a > b ? b : a;
}
*/

為什么第二種方式更“合適”?

對於大多數情況,超載工作正常,AFAIK是建議的基線方法。 (參見juanchopanza建議的GOTW)

如果有人明確要求輸入模板,則調用min<int>(x, y) 在這種情況下,忽略重載並且僅考慮模板(基礎或專用)。

暫無
暫無

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

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