The template function gives the error "no match for the call"

The first question is about stackoverflow :) I'm relatively new to C ++ and have never used templates, so forgive me if I do something stupid. I have a template function that combes a list and checks for a specific element of a general type. That way I can indicate if it is looking for a string, or int, or something else.

template <class T>   
bool inList(T match, std::string list)  
{
    int listlen = sizeof(list);
    for (int i = 0; i <= listlen; i++) {
        if (list[i] == match) return true;
        else continue;
    }
    return false;
};

This is my challenge inList(). testvecis a string vector with several elements, including "test":

if (inList<string>("test", testvec))
    cout << "success!";
else cout << "fail :(";

To my horror and confusion, when I compile, I hit with the following error:

error: no matching function for call to 'inList(const char [5], std::vector<std::basic_string<char> >&)'

What am I doing wrong?: (

[EDIT] , . ( , , , , -:()

0
1

, std::vector std::string. .

, , . , , , , deque... , (, , ++ 1x !). . .

++ 11 ( , ):

template<class elem_t, class list_t>
bool in_list(const elem_t& elem, const list_t& list) {
   for (const auto& i : list) {
      if (elem == i) {
         return true;
      }
   }
   return false;
}

EDIT: std:: initializer_list , :

template<class elem_t>
bool in_list(const elem_t& elem, std::initializer_list<elem_t> list) {
   for (const auto& i : list) {
      if (elem == i) {
         return true;
      }
   }
   return false;
}

:

int main() {
   std::vector<int> a = {1, 2, 3, 4, 5};
   std::cout << in_list(3, a) << std::endl;
   std::string b = "asdfg";
   std::cout << in_list('d', b) << std::endl;
   std::cout << in_list('d', "asdfg") << std::endl;
   std::cout << in_list(3, {1, 2, 3, 4, 5}) << std::endl;
   return 0;
}

, ++ 98, , , . .

template<class elem_t, class list_t>
bool in_list_98(const elem_t& elem, const list_t& list) {
   list_t::const_iterator end = list.end(); //prevent recomputation of end each iteration
   for (list_t::const_iterator i = list.begin(); i < end; ++i) {
      if (elem == *i) {
         return true;
      }
   }
   return false;
}

STL:

template<class elem_t, class iterator_t>
bool in_list_stl(const elem_t& elem, iterator_t begin, iterator_t end) {
   for (iterator_t i = begin; i < end; ++i) {
      if (elem == *i) {
         return true;
      }
   }
   return false;
}
//call like std::string s = "asdf"; in_list_stl('s', s.begin(), s.end());

, , ...

+4

All Articles