Reputation: 1
I am trying to use a container (std::vector
, std::list
, std::map
, etc...) on a function template but I keep getting an error saying "No suitable user-defined conversion exists"
I tried making a different function template, print_container()
with 1 argument, and it works.
#include "stdafx.h"
#include <iostream>
#include <vector>
template<typename T>
using Iterator = typename T::iterator;
template<typename C, typename V>
std::vector<Iterator<C>> find_all(C& container, V value) {
std::vector<Iterator<C>> res;
for (auto p = container.begin(); p != container.end(); ++p)
if ((*p) == value)
res.push_back(p);
return res;
}
int main() {
std::vector<int> vec1 = { 1, 2, 3 };
std::vector<Iterator<int>> res = find_all(vec1, 1); // does not work
return 0;
}
find_all()
should return a std::vector
of iterators with only 1 iterator, the iterator attached to vec1[0]
and assign that vector to res
.
Upvotes: 0
Views: 97
Reputation: 310990
The template argument of the Iterator in this declaration
std::vector<Iterator<int>> res = find_all(v, 1);
Is invalid. The type int
has no iterators. See this alias declaration
template<typename T>
using Iterator = typename T::iterator;
You should write either
std::vector<Iterator<std::vector<int>>> res = find_all(v, 1);
or
auto res = find_all(v, 1);
Upvotes: 1
Reputation: 206607
The return type is std::vector<Iterator<std::vector<int>>>
, not std::vector<Iterator<int>>
.
std::vector<Iterator<std::vector<int>>> res = find_all(vec1, 1);
Use of auto
is better for cases like this.
auto res = find_all(vec1, 1);
Upvotes: 2
Reputation: 66200
The problem is in the returned type
std::vector<Iterator<int>> res = find_all(vec1, 1);
//...................^^^ wrong
From that call you obtain a vector of iterators of std::vector<int>
, not of int
std::vector<Iterator<std::vector<int>>> res = find_all(vec1, 1);
//...................^^^^^^^^^^^^^^^^ correct
To avoid this sort of problems, usually you can use auto
(starting from C++11)
auto res = find_all(vec1, 1);
Upvotes: 2