Если я создаю std::vector и инициализирую его двумя способами, оба вызывают std::initializer_list конструктор.
Код: Выделить всё
std::vector v1{1, 2, 3}; // Calls vector(initializer_list< int >)
std::vector v2 = {1, 2, 3}; // Calls vector(initializer_list< int >)
Код: Выделить всё
struct Imp { Imp(int) {} };
Код: Выделить всё
std::vector v3{1, 2, 3}; // Calls vector(initializer_list< Imp >)
std::vector v4 = {1, 2, 3}; // Calls vector(const int*, const int* ) ???
Почему синтаксис = { вызывает вектор(const int*, const int*) в GCC?
Дальнейшее исследование
Я попробовал создать собственный шаблон класса с обоими конструкторами:
Код: Выделить всё
template
struct Custom {
Custom(std::initializer_list) {}
Custom(const int*, const int*) {}
};
Код: Выделить всё
Custom v5{1, 2, 3}; // Calls Custom(initializer_list< Imp >)
Custom v6 = {1, 2, 3}; // Calls Custom(initializer_list< Imp >)
Случай 1 — предоставить только инициализатор_list ctor
Код: Выделить всё
template
struct std::vector {
vector(initializer_list) {}
};
Код: Выделить всё
std::vector v7{1, 2, 3}; // Calls vector(initializer_list< Imp >)
std::vector v8 = {1, 2, 3}; // Calls vector(initializer_list< Imp >)
Код: Выделить всё
template
struct std::vector {
vector(const int*, const int*) {}
};
Код: Выделить всё
std::vector v9{1, 2, 3}; // Error - no matching ctor
std::vector vA = {1, 2, 3}; // Error - no matching ctor
Код: Выделить всё
template
struct std::vector {
vector(initializer_list) {}
vector(const int*, const int*) {}
};
Код: Выделить всё
std::vector vB{1, 2, 3}; // Calls vector(initializer_list< Imp >)
std::vector vC = {1, 2, 3}; // Calls vector(const int*, const int*) ???
В случай 3 как предоставление конструктора Initializer_list позволяет вызывать конструктор const int*?
Подробнее здесь: https://stackoverflow.com/questions/793 ... -different