2013-06-27 108 views
5

從一些幻燈片模板左右專業化:模板功能專業化與超載

#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; 
} 
*/ 

爲什麼第二種方式更「合適」?

+2

相關閱讀:[爲什麼不專業化功能模板?](http://www.gotw.ca/publications/mill17.htm) – juanchopanza

+0

這些幻燈片是否在線提供? –

+0

@Vaughn在Dropbox文件夾中... – nodwj

回答

1

過載對大多數上下文都很有效,AFAIK是建議的基準方法。 (參見juanchopanza建議的GOTW

如果有人明確要求模板,則區別命中min<int>(x, y)。在這種情況下,重載將被忽略,只考慮模板(基礎或專用)。

+0

另外,如果有人使用另一個模板內的功能。 – Daemin

+1

@Daemin:你可以擴展你的意思嗎? –

+0

在函數'template T foo(const T&a,const T&b)'它們調用'min (a,b);'因此它將使用模板版本,而不管任何非模板化的重載。 – Daemin