c++ - 什么是 C++17 中的 std::vector 推导指南?

标签 c++ templates vector c++17 template-argument-deduction

我阅读了 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 a vector<int> or a vector<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 .该标准似乎从迭代器对中定义了一个明确的推导指南:

enter image description here

无论如何,g++ 8 中遇到的行为似乎都是正确的,因为 (引用 Rakete1111 )

  • overload resolution prefers the constructor with std::initializer_list with the braced initializer list

  • other 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/

相关文章:

c++ - 为每个算法传递多个函数

c++ - std::string 未在 Eclipse/CDT 8.0 中解析

c++ - 嵌套类名在封闭类模板中使用时是否被视为当前实例化

C++ "if then else"模板替换

C++11 "late binding"模板参数

c++ - 基于容器范围的构造函数效率

java - 计算 Swing 中物体之间可能的路径(可能是无穷大)的策略?

c++ - 在boost中为动态数组定义自定义步进器

c++ - 启用 c++11 时 c++ 递归模板的奇怪行为

c++ - 欧拉计划问题 12 - C++