2014-02-24 19 views
1

區別值的模板功能,我想有一個模板功能contains其中有兩個可能的定義,取決於第二式:使從上游

template <typename ElementType, typename CollectionType> 
bool contains(const CollectionType & collection, ElementType element) 
{ 
    return collection.end() != std::find(collection.begin(), collection.end(), element); 
} 

template <typename CollectionType, typename PredicateType> 
bool contains(const CollectionType & collection, PredicateType predicate) 
{ 
    return collection.end() != std::find_if(collection.begin(), collection.end(), predicate); 
} 

標準庫經常使用_if來區分謂詞和算法的價值版本 - 例如findfind_if

理想情況下,我希望編譯器找出使用哪一個。畢竟,上面兩個模板是用於非常不同的用途 - ElementType和PredicateType的類型是非常不同的域。

有沒有一種很好的方法通過模板shenanigans來完成這個工作?或者我堅持爲上面的函數找到兩個不同的名字?

+3

如果您的容器包含謂詞,該怎麼辦? –

+0

好點。也許如果沒有明確的名稱差異就無法解決這個問題。 – Mordachai

+1

不確定但在第一種情況下使用'std :: enable_if ,ElementType> :: type'作爲'ElementType'可能會消除歧義。 – Kiwi

回答

4

如果你的容器發揮不錯,並定義成員value_type S,那麼你可以做的「元素」超載更爲具體:如果容器定義begin/end功能

template <typename C> 
bool contains(C const & collection, typename C::value_type const & element); 

template <typename C, typename P> 
bool contains(C const & collection, P predicate); 

更神祕的方法可能會被檢查,並推導這些元素的類型。一般來說,確定給定類型是否是容器是相當棘手的...

+0

這種排序的方法總是幾乎適用於我。我經常發現我試圖檢測一個集合是否包含可比的東西,但不是包含的確切類型。因此它試圖解析到第二個模板,並失敗。 :( – Mordachai

+0

但是,謝謝你的想法! – Mordachai

+0

@Mordachai:[漂亮的打印機代碼](http://stackoverflow.com/questions/4850473/pretty-print-c-stl-containers)試圖有點更聰明什麼是容器,如果有什麼幫助的話...... –