Если я создаю 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*?
EDIT
Был задан вопрос, как я знать, какой конструктор вызывается. Это началось, когда я изучал, когда вызываются конструкторы копирования и перемещения. std::initializer_list невозможно переместить. Но вот несколько дополнительных примеров с отпечатками.
Пример 1 – Использование отдельного типа
Код: Выделить всё
struct Imp { Imp(int) {} };
template
struct Custom {
Custom(std::initializer_list) { std::printf("initializer_list\n"); }
Custom(const int*, const int*) { std::printf("const int*, const int*\n"); }
};
int main(int argc, char *argv[]) {
Custom v{1, 2, 3};
Custom w = {1, 2, 3};
Код: Выделить всё
initializer_list
initializer_list
Код: Выделить всё
struct Imp { Imp(int) {} };
template
struct std::vector {
vector(initializer_list) { std::printf("initializer_list\n"); }
vector(const int*, const int*) { std::printf("const int*, const int*\n"); }
};
int main(int argc, char *argv[]) {
std::vector v{1, 2, 3};
std::vector w = {1, 2, 3};
Код: Выделить всё
initializer_list
const int*, const int*
Почему это изменит название перегрузки ctor?
Подробнее здесь: https://stackoverflow.com/questions/793 ... -different