區別值的模板功能,我想有一個模板功能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來區分謂詞和算法的價值版本 - 例如find
和find_if
。
理想情況下,我希望編譯器找出使用哪一個。畢竟,上面兩個模板是用於非常不同的用途 - ElementType和PredicateType的類型是非常不同的域。
有沒有一種很好的方法通過模板shenanigans來完成這個工作?或者我堅持爲上面的函數找到兩個不同的名字?
如果您的容器包含謂詞,該怎麼辦? –
好點。也許如果沒有明確的名稱差異就無法解決這個問題。 – Mordachai
不確定但在第一種情況下使用'std :: enable_if,ElementType> :: type'作爲'ElementType'可能會消除歧義。 –
Kiwi