【发布时间】:2015-04-08 17:06:49
【问题描述】:
我编写了以下模板函数,它检查任意容器是否包含特定元素:
template<template<class, class...> class container_t, class item_t, class... rest_t>
bool contains(const container_t<item_t, rest_t...> &_container, const item_t &_item) {
for(const item_t &otherItem : _container) {
if(otherItem == _item) { return true; }
}
return false;
}
这适用于大多数容器。然而,对于所有类型的集合(和地图)来说,它是次优的,因为我们可以使用:
template<template<class, class...> class set_t, class item_t, class... rest_t>
bool contains(const set_t<item_t, rest_t...> &_set, const item_t &_item) {
return _set.count(_item) > 0;
}
显然,由于模棱两可,我们不能同时使用这两个模板。现在我正在寻找一种方法,如果container_t 不提供count 成员函数,则使用std::enable_if 启用第一个模板,如果提供,则启用第二个模板。但是我不知道如何检查特定的成员函数(使用 C++11)。
【问题讨论】:
-
如果您愿意将 boost 添加为依赖项,那么 boost.TTI 可以在
BOOST_TTI_HAS_MEMBER_FUNCTION宏中找到您想要的内容 -
您确定要这样做吗?在标准库中,当您进行线性搜索和使用更有效的机制时,它们让您准确地拼出您想要使用的
find形式,以便明确明确。附带说明一下,如果您确实想这样做,请务必使用find而不是count,这只是避免过早悲观。 -
@SimonGibbons:谢谢,它看起来像我需要的。但是,我现在不希望依赖于 boost。
-
@MarkB:据我所知
std::find也使用不同的算法,这取决于我们是否有一个有序的容器,不是吗?至少en.cppreference.com/w/cpp/algorithm/find 写道,复杂性至多是线性的,即对于合适的容器来说可能小于线性。但是,如果我错了,请纠正我。 -
@Haatschii 该标准只是说“至多最后一个比较”,因此假设它对所有容器类型都是线性的。
标签: c++ templates c++11 sfinae