Если я создаю std :: vector и инициализации его двумя способами, оба вызывают std :: initializer_list Конструктор. < /p>
Код: Выделить всё
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?
Дальнейшее исследование < /h2>
Я попытался создать свой собственный шаблон класса, который имеет оба конструктора: < /p>
Код: Выделить всё
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*) ???
< /code>
Вот где я потерян.
в [b] case 3 < /strong> < /em>, как Предоставление инициализатора_листа
Код: Выделить всё
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? Vector со строкой литералы много раз, используя v {} и v = {} синтаксисы.
на моем i9- 10885H:
gcc 14.2
Код: Выделить всё
v{} 0.820 seconds
v={} 0.444 seconds
v={} took 54.1% as long as v{}
Код: Выделить всё
v{} 0.819 seconds
v={} 0.842 seconds
v={} took 102.8% as long as v{}
Подробнее здесь: https://stackoverflow.com/questions/793 ... -different