gpt4 book ai didi

C++17 几乎一致的初始化

转载 作者:行者123 更新时间:2023-11-28 01:34:28 31 4
gpt4 key购买 nike

在本视频的结尾(从 15:57 开始)有关于如何在 C++17 中使用几乎一致的初始化的建议:video here

要点是这样的:始终使用直接初始化 auto a{...};MyType a{...};不要使用复制初始化= {...}为你的类型。

#include <iostream>


struct MyType {
explicit MyType(std::initializer_list<int>) {
std::cout << "Called std::initializer_list<int>" << std::endl;
}

explicit MyType(int) {
std::cout << "Called int." << std::endl;
}

MyType(int, int, int) {
std::cout << "Called int, int, int" << std::endl;
}
};



int main() {
MyType calls_init_list{10}; //Calls initializer_list<int>
MyType calls_init_list_2{10, 20}; //Calls initializer_list<int>
MyType calls_init_list_3{10, 20, 30}; //Calls initializer_list<int>

MyType compile_error = {10, 20, 30}; //Compile error
}

如果我从第一个构造函数中删除 explicit ,它将调用第 4 次调用也使用 initializer_list<int>

  1. 我需要做哪些更改才能调用 (int)(int, int, int)遵守视频中的规则?
  2. 是否有可能在存在初始化列表构造函数的情况下调用其他构造函数?
  3. 有什么设计建议可以避免放弃视频中建议的一般规则吗?最终有一些有意义的东西会很好,C++ 初始化可能是其中最糟糕的部分。

最佳答案

What changes should I need for being able to call (int) and (int, int, int) following the rule in the video?

删除 initializer_list<int>构造函数。这是让它发挥作用的唯一方法。

Is it even possible to call the other constructors in the presence of the initializer list constructor?

是的,只要braced-init-list中的类型不能匹配任何initializer_list<T>中的类型构造函数。他们总是具有首要地位。

因此它被戏称为“几乎统一初始化”。

典型的解决方案是向非 initializer_list 添加一些标签类型构造函数:

struct tag_t {};
constexpr inline tag_t tag;

struct MyType {
explicit MyType(std::initializer_list<int>) {
std::cout << "Called std::initializer_list<int>" << std::endl;
}

MyType(tag_t, int) {
std::cout << "Called int." << std::endl;
}

MyType(tag_t, int, int, int) {
std::cout << "Called int, int, int" << std::endl;
}
};

int main() {
MyType three_int = {tag, 10, 20, 30}; //Calls 3-`int` constructor
}

any design recommendations to avoid abandoning the general rule adviced in the video?

好吧,考虑到“一般规则”不是一个好的规则(他的幻灯片包含典型的反例:尝试用大括号调用 vector<int> 的大小+值版本),最好放弃它。关于什么的小问题auto a{2};翻译成与字面上无法调用某些构造函数无关。

关于C++17 几乎一致的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49952301/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com