[英]error cannot convert 'coll' (type 'std::__cxx11::list<char>') to type 'const char&'
here I'm trying to implement a generic function to print all elements of a container but I am getting following errors,在这里,我试图实现一个通用函数来打印容器的所有元素,但出现以下错误,
#include<iostream>
#include<list>
using namespace std;
template <typename T>
void print_elements(const T& coll)
{
for (const auto& elem : coll)
{
std::cout << elem << ' ';
}
}
int main()
{
list<char> coll; // list container for character elements
//appenading a to z using lists
for (char i = 'a'; i <= 'z'; ++i)
{
coll.push_back(i); //using the push back function
}
for (auto elem : coll) // in this case we have to use a range based for loop
{
cout << elem << ' ';
}
cout << endl;
cout << coll.size();
print_elements<char>(coll);
return 0;
}
I am also getting these errors:我也收到这些错误:
candidate: 'template void print_elements(const T&)' void print_elements(const T& coll) template argument deduction/substitution failed:候选:'template void print_elements(const T&)' void print_elements(const T& coll) 模板参数推导/替换失败:
no matching function for call to 'print_elements(std::__cxx11::list&)'没有匹配的函数调用'print_elements(std::__cxx11::list&)'
print_elements(coll);打印元素(科尔);
I think the error is in this line我认为错误在这一行
print_elements<char>(coll);
Change this to将此更改为
print_elements<list<char>>(coll);
or you may put like this或者你可以这样放
print_elements(coll);
Error is in the following line错误在以下行
print_elements<char>(coll);
because you specify that the template function parameter is of type char
but you coll
is not of type char
but of type std::list<char>
.因为您指定模板函数参数是char
类型,但您coll
不是char
类型,而是std::list<char>
。
Therefore, you need to either pass correct parameter type like:因此,您需要传递正确的参数类型,例如:
print_elements< std::list<char> >(coll);
or let the template argument deduction determine template arguments types automatically like:或者让模板参数推导自动确定模板参数类型,例如:
print_elements(coll);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.