从初始化列表中推导构造函数的模板参数

Ren*_*ter 3 c++ language-lawyer template-argument-deduction c++17

Kona会议上,构造函数的模板参数推导(P0091R0)已获得批准。它简化了一些变量定义:

std::pair   p  {1,2};     // o.k., constructor pair<int,int>(1,2)
std::vector v1 (10, 0);   // o.k., 10 zeroes, constructor vector<int>(size_t n, T initvalue)
std::vector v2 {10, 0};   // o.k., 2 values: 10, 0, apparently initializer list?
std::vector v3 = {10, 0}; // o.k., same as v2?
Run Code Online (Sandbox Code Playgroud)

但是,以下行不会在 gcc 7 HEAD 201611 版本中编译(实时示例):

std::vector v4 = {3};     // error: no matching function for call to 'std::vector(int)'
std::vector v5 {1, 2, 3}; // error: 'int' is not a class
std::set    s  {1, 2, 3}; // error: no matching function for call to 'std::set(int,int,int)'
Run Code Online (Sandbox Code Playgroud)

由于它们涉及初始值设定项列表,这些是否只是“一座太过遥远的桥梁”?它们是否包含在模板类型参数推导中?当编译器符合 C++1z 时,它们会被允许吗?

Vit*_*meo 5

您需要一对额外的大括号才能使您的代码正常工作:

std::vector v4 = {{1, 5}}; 
std::vector v5 {{1, 2, 3}};  
std::set    s  {{1, 2, 3}};
Run Code Online (Sandbox Code Playgroud)

  • 这与聚合初始化到底有什么关系?任何地方都没有聚合。 (2认同)