2010-01-16 33 views
2

在C++編程語言的340頁:特別版,斯特勞斯寫道...默認模板的語義檢查參數

The semantic checking of a default argument for a template parameter is done if and (only) when that default argument is actually used. In particular, as long as we refrain from using the default template argument Cmp<T> we can compare() strings of a type for which Cmp<X> wouldn't compile (say, because < wasn't defined for an X). This point is crucial in the design of the standard containers, which rely on a template argument to specify default values.

我有麻煩纏繞我的頭圍繞這一用法。爲什麼這個規則允許比較類型X的字符串,通常情況下它不會被編譯?這種行爲不會不受歡迎嗎?

回答

2

給出的例子是:

template<class T, class C = Cmp<T> > 
int compare(const String<T>& str1, const String<T>& str2) 
{ 
    // ... compare using C 
} 

的想法是,類模板Cmp可能不被定義或對一些T非法的。在這種情況下,你可以通過自定義比較類模板:

compare<char, MyComparer>(str1, str2); 

如果你這樣做,Cmp未使用,將不檢查是否確實會編譯。

0

這就是說(例如)如果參數默認爲X,但是您指定了T,那麼X的語義不會被檢查。這很重要,因爲X可能不會編譯(就像它說的那樣,因爲某些運算符可能不會在X上定義)。

例如

template <class T = int> 
struct foo 
{ 
    static int bar(T x) { return x.size(); } 
} 

int main() 
{ 
    std::cout << foo<std::string>::bar("hello") << std::endl; 
} 

即使.size()未定義爲int,也不會導致錯誤。它不會導致錯誤,因爲int的默認參數並未實際使用。

回答你的問題。這並不是說它會允許X進行比較,而是說如果使用T,那麼X的比較是否可以進行比較並不重要,因爲您不使用X.