我阅读了 std::vector
的扣除指南从使用 cppreference .
示例:
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3, 4};
std::vector x{v.begin(), v.end()}; // uses explicit deduction guide
}
所以,我对此有一些疑问:
什么是
std::vector
C++17 中的推导指南?为什么以及何时需要 vector 推导?
这里是
x
一个std::vector<int>
或std::vector<std::vector<int>>
?
最佳答案
What are
std::vector
deduction guides in C++17?
用户定义的扣除指南允许用户决定如何class template argument deduction从模板类的构造函数参数推导出参数。在这种情况下,似乎 std::vector
有一个明确的指南,应该使迭代器对的构造更加直观。
Why and when do we need vector deduction?
我们并不“需要”它,但它在通用代码和非常明显的代码中很有用(即显式指定模板参数对读者不利的代码)。
Is
x
avector<int>
or avector<vector<int>>
?
这是一个快速解决这个问题的好方法 - 编写一个没有定义的模板函数声明并尝试调用它。编译器将打印出传递参数的类型。这是 g++ 8 打印出来的内容:
template <typename>
void foo();
// ...
foo(x);
error: no matching function for call to
foo(std::vector<__gnu_cxx::__normal_iterator<int*, std::vector<int> > ...
从错误消息中可以看出,x
推导出为 std::vector<std::vector<int>::iterator>
.
Why?
std::vector
的扣分攻略are available on cppreference.org .该标准似乎从迭代器对中定义了一个明确的推导指南:
无论如何,g++ 8 中遇到的行为似乎都是正确的,因为 (引用 Rakete1111 )
overload resolution prefers the constructor with
std::initializer_list
with the braced initializer listother constructors are considered only after all
std::initializer_list
constructors have been tried in list-initialization
std:vector<std::vector<int>::iterator>
因此是使用列表初始化时的正确结果。 live example
在构建 x
时与 std::vector x(v.begin(), v.end())
, int
将被推导出来。 live example
关于c++ - 什么是 C++17 中的 std::vector 推导指南?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45995902/