#include <boost/type_index.hpp>
#include <iostream>
#include <vector>
int main()
{
std::vector v{2, 3.14};
std::cout << boost::typeindex::type_id_with_cvr<decltype(v)>().pretty_name() << '\n';
std::cout << "size: " << v.size() << '\n';
for (auto x : v)
std::cout << "- " << x << '\n';
}
Run Code Online (Sandbox Code Playgroud)
输出是:
#include <boost/type_index.hpp>
#include <iostream>
#include <vector>
int main()
{
std::vector v{2, 3.14};
std::cout << boost::typeindex::type_id_with_cvr<decltype(v)>().pretty_name() << '\n';
std::cout << "size: " << v.size() << '\n';
for (auto x : v)
std::cout << "- " << x << '\n';
}
Run Code Online (Sandbox Code Playgroud)
std::vector实例化使用自动类型推导(CTAD)。
显然,initializer_list构造函数已被使用(检查),但为什么它同时接受 anint和 adouble并且仍然将类型推导为vector<double>?
如果我增加元素数量(同时混合int和double),编译将失败。
gcc和 的结果相同clang
std::vector<double, std::allocator<double> >
size: 2
- 2
- 3.14
Run Code Online (Sandbox Code Playgroud)
chr*_*ris 23
这里发生了两个重载解析实例。第一个是推导模板参数。由于 init-list 中的两种类型不同,因此此处选择 size+value 构造函数(或更正式地说,从所述构造函数生成的推导指南),将类型推导为double。
然后重载解析再次运行以创建对象。现在类型称为double,列表构造函数现在有效,因此可用于初始化对象。