【发布时间】:2018-05-23 14:34:04
【问题描述】:
我有这个代码:
#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'。
我想知道在 C++11 及更高版本中编写此代码的正确方法是什么。
【问题讨论】:
-
` 因为 C++11 我们应该尝试在任何地方使用 auto` - 不。 AAA 是个糟糕的主意。 C++11 中正确惯用的方式是 C++17 中的
std::vector<int> w{1, 2, 3};和std::vector w{1, 2, 3}。 -
对于 AAA,
auto w = std::vector<int>{1, 2, 3};... -
你的
auto w被自动识别为initializer_list,这是合理的。您不能指望编译器将其识别为std::vector<int>,因为{x, x, x}不一定是vector(可能是任何类型的容器或原始数组)并且x不一定是int。 -
为什么提供一个不起作用的代码并要求一种基于意见的修复方法?我相信最多有两到三种方法可以解决它。如果答案中记录了这两种或三种方式,那么它应该是一个客观的答案。
标签: c++ c++11 initializer-list auto