C++11 统一初始化 : ambiguity between initializer list and multiple-parameter constructors?

标签 c++ c++11

目前正试图围绕 C++11 的统一初始化进行思考。我遇到了这个模棱两可的情况:考虑一个类,它可以由两个参数的构造函数或任意长度的初始化列表构造:

class Foo {
  public:
    Foo(int a, int b) {
      std::cout << "constructor 1" << std::endl;
    }
    Foo(std::initializer_list<int>) {
      std::cout << "constructor 2" << std::endl;
    }
};
遵循统一的初始化约定,我希望以下内容起作用:Foo a (1, 2)版画 constructor 1 (废话)Foo b {1, 2}版画 constructor 1Foo c = {1, 2}版画 constructor 2但是,编译器似乎解释了 Foo b {1, 2}作为列表初始化,并调用构造函数2。是()当存在初始化列表构造函数时,语法是强制编译器考虑其他类型构造函数的唯一方法吗?

最佳答案

您可以向构造函数添加一个额外的忽略参数,以在调用站点指定特定的重载,就像在 STL 中所做的那样:

#include <iostream>

struct non_init_list_t {};
inline constexpr non_init_list_t non_init_list;

struct Class {
    Class(int a, int b, non_init_list_t = non_init_list) { std::clog << "()\n"; }
    Class(std::initializer_list<int> list) { std::clog << "{}\n"; }
};

Class a{12, 42, non_init_list};  // ()
Class b{12, 42};                 // {}
Class c(12, 42);                 // ()

关于C++11 统一初始化 : ambiguity between initializer list and multiple-parameter constructors?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64147464/

相关文章:

c++ - C 语言中是否有像 STL( vector 、 map ...)这样的库?

c++ - 如何检查ACL是否被保护

c++ - 使用模板进行序列数组初始化

c++ - 模板编程 : specialization and enable_if

C++11 可变参数模板在类中调用函数

c++ - 如何集成使用表达式模板的库?

c++ - 类 POD 成员默认初始化与零初始化与无初始化?

c++ - 在 [现代] C++ 中通过 N 个变量进行范围/循环

c++ - 是否可以使用元组中传递的参数的所有可能 K 组合(重复)来调用方法?

c++ - 为什么这个模板函数没有按预期运行?