gpt4 book ai didi

c++ - 创建一个区分值和谓词的模板函数

转载 作者:行者123 更新时间:2023-11-30 01:54:27 24 4
gpt4 key购买 nike

我想要一个模板函数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 的类型是完全不同的域。

是否有通过模板恶作剧来完成此任务的好方法?还是我一直在为上面包含的函数寻找两个不同的名称?

最佳答案

如果您的容器运行良好并定义了成员 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com