作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想要一个模板函数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 的类型是完全不同的域。
是否有通过模板恶作剧来完成此任务的好方法?还是我一直在为上面包含的函数寻找两个不同的名称?
最佳答案
如果您的容器运行良好并定义了成员 value_type
,那么您可以使“元素”重载更具体:
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);
更神秘的方法可能是检查容器是否定义了 begin
/end
函数并从中导出元素类型。通常,确定给定类型是否为容器是相当棘手的...
关于c++ - 创建一个区分值和谓词的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21992514/
我是一名优秀的程序员,十分优秀!