遍历通用STL容器以检查是否存在

时间:2016-08-08 01:51:18

标签: c++ templates c++11 stl

我尝试编写模板函数,如果给定对象已经存在于容器中,则返回true。这就是我所处的地方,我不知道从哪里开始。

 template <typename BeginningIter, typename EndingIter, typename T>
 static bool itemExists(BeginningIter bit, EndingIter eit, const T &searchTerm)
 {
     if ((bit == nullptr) || (eit == nullptr)) {
         return false;
     }  
     static_assert(std::is_same<std::decay(decltype(*bit)), std::decay(searchTerm)>::value, "Invalid");
     for (auto iter = bit; iter != eit; iter++) {
         if (*iter == searchTerm) {
             return true;
         }
     }
     return false;
}

我也尝试在模板规范行中使用std :: enable_if,但我不知道如何获得解除引用的BeginningIter术语的类型。我使用了std :: decay,以防它指向引用类型。但是,在尝试编译时,我得到了

generalutilities.h: In static member function ‘static bool GeneralUtilities::itemExists(BeginningIter, EndingIter, const T&)’:
generalutilities.h:148:77: error: template argument 1 is invalid
         if (!std::is_same<std::decay(decltype(*bit)), std::decay(searchTerm)>::value) {
                                                                             ^
generalutilities.h:148:77: error: template argument 2 is invalid

1 个答案:

答案 0 :(得分:1)

 std::decay(decltype(*bit))

std::decay不是一个功能;这是一个元功能。 IE:具有::type成员的结构(或导致值的元函数的::value)。而且无论如何都不能通过传递类型来调用常规函数。

您使用typename std::decay<decltype(*bit)>::type调用元函数。 typename部分非常重要。

Pre-C ++ 14,您可以通过创建快速别名模板来缩短代码:

template<typename T> using decay_t = typename std::decay<T>::type;

C ++ 14为所有类型元函数制作了标准库的一部分。