[英]Function Template not working, getting error “No suitable user-defined conversion”
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"我正在尝试在 function 模板上使用容器( std::vector
、 std::list
、 std::map
等...),但我不断收到错误消息,提示“不存在合适的用户定义转换”
I tried making a different function template, print_container()
with 1 argument, and it works.我尝试制作一个不同的 function 模板,print_container print_container()
和 1 个参数,它可以工作。
#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
. find_all()
应该返回一个只有 1 个迭代器的迭代器的std::vector
,该迭代器附加到vec1[0]
并将该向量分配给res
。
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<int>
的迭代器向量,而不是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
(从 C++11 开始)
auto res = find_all(vec1, 1);
The return type is std::vector<Iterator<std::vector<int>>>
, not std::vector<Iterator<int>>
.返回类型是std::vector<Iterator<std::vector<int>>>
,而不是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
更好。
auto res = find_all(vec1, 1);
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. int
类型没有迭代器。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.