C ++错误:没有匹配的函数来调用'print_size' [英] C++ error: no matching function for call to 'print_size'
问题描述
我有此代码:
#include <iostream>
#include <vector>
template<typename T>
void print_size(std::vector<T> a)
{
std::cout << a.size() << '\n';
}
int main()
{
std::vector<int> v {1, 2, 3};
print_size(v);
auto w = {1, 2, 3};
// print_size(w); // error: no matching function for call to 'print_size'
// candidate template ignored: could not match 'vector' against 'initializer_list'
}
...它将编译并运行,没有任何问题.但是,如果启用注释行,则会产生错误no matching function for call to 'print_size'
.
...which compiles and runs without any issues. But if I enable the commented-out line, it produces the error no matching function for call to 'print_size'
.
我想知道用C ++ 11和更高版本编写此代码的正确方法是什么.
I would like to know what is the correct way to write this code in C++11 and later versions.
推荐答案
对于auto w = {1, 2, 3};
,w
的类型将为std::initializer_list<int>
,并且print_size(w);
失败,因为无法推导模板参数T
. 模板参数推导不考虑隐式转换.
For auto w = {1, 2, 3};
the type of w
will be std::initializer_list<int>
, and print_size(w);
fails because template parameter T
can't be deduced; template argument deduction does not consider implicit conversions.
类型推导不考虑隐式转换(上面列出的类型调整除外):这是超载解析的工作,稍后会发生.
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
您可以显式指定模板参数
You can specify template argument explicitly,
print_size<int>(w);
或者您也可以将w
设置为std::vector<int>
;如果您坚持使用auto
,则需要明确指定类型.
Or you can make w
to be a std::vector<int>
instead; and if you persist using auto
you need to specify the type explicitly.
auto w = std::vector<int>{1, 2, 3};
print_size(w);
这篇关于C ++错误:没有匹配的函数来调用'print_size'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!