为什么不对 initializer_list 中的值进行类型检查?

Why aren't values in initializer_list type-checked?

如何编译并且 运行 没有任何警告或错误?我不明白如何将 current 的取消引用值(一个 int)毫无问题地分配给字符串 a

class Test {
public:
  string a;

  Test(initializer_list<int> t) {
    auto current = t.begin();

    // I am assigning an int to a string!
    a = *current;
  }
};

int main() {
  Test test{65};
  printf("%s\n", test.a.c_str());
}

打印出来的字符串是

A

相比之下,这段非常相似的代码会产生编译时错误:

int main() {
  initializer_list<int> test1{65};
  auto current = test1.begin();
  string b = *current;

  return 0;
}

错误是:

error: no viable conversion from 'const int' to 'std::__1::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >')
  string b = *current;

请注意 a = *current;string b = *current; 执行不同的操作。

a = *current;是一个赋值,导致operator=的调用,std::string::operator= has an overloading taking char, which makes a = *current; work (after the implicit conversionintchar).

4) Replaces the contents with character ch as if by assign(std::addressof(ch), 1)

string b = *current;是一个初始化,它试图调用constructor of std::string来初始化b。但是这些构造函数没有这样的重载取int(或char),那么string b = *current;就不行了。