c++ - std::array的演绎指南

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

我仔细阅读了C++模板独特的书,并尝试了解std::array的推论指南。
关于标准的定义,以下是声明

template <class T, class... U>
array(T, U...) -> array<T, 1 + sizeof...(U)>;

例如,如果在主数组创建为
std::array a{42,45,77} 

扣除如何进行?

谢谢

最佳答案

How the deduction takes place?



这很简单。

呼唤
std::array a{42,45,77}

比赛
array(T, U...)

带有T = decltype(42)U... = decltype(45), decltype(77)T = intU... = int, int

因此a{42,45,47}的类型变为array<T, 1 + sizeof...(U)>,因此std::array<int, 1 + sizeof...(int, int)>,即std::array<int, 1 + 2>std::array<int, 3>
换句话说:提取参数的类型;第一个(T)用于为类型指定数组(第一个模板参数);其他仅用于计数(sizeof...(U))。但是,对于模板的第二个参数,同样要计算第一个参数(T类型,因此1中的1 + sizeof...(U))也很重要。

关于c++ - std::array的演绎指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62095630/

相关文章:

c++ - BFS 实现无法正常工作

c++ - .tpp 文件中的 doxygen 和模板问题

c++ - 使用指向方法的指针的 MSVC 编译器 fatal error C1001

c++ - Visual Studio : C++ Project Include Paths sharing over Repository

c++ - Visual Studio 作为代码浏览器 : How to preserve the directory structure?

c++ - 实现同时具有枚举和类行为的东西

c++ - 检测类型是否为 std::tuple?

c++ - 具有std::enable_if_t的模板类,静态const成员初始化

C++17 std::variant 头文件 (clang 6.0.0)

c++ - 函数中的自动参数类型