如何“减少输入以创建 C”类型”使用统一初始化器?

发布于 2024-12-05 00:21:14 字数 604 浏览 1 评论 0原文

我用 {} 玩过很多新的统一初始化。像这样:

vector<int> x = {1,2,3,4};
map<int,string> getMap() {
    return { {1,"hello"}, {2,"you"} };
}

毫无争议的是,这个初始化可能会改变我们的C++编程。 但我想知道在阅读 Herb Sutter 常见问题解答

Alfonse:统一初始化(在可以推导出正在构造的类型时使用 {} 调用构造函数)有可能从根本上减少创建 C++ 类型所需的键入量。它就像 lambda 一样,将改变人们编写 C++ 代码的方式。 [...]

有人能给我举个例子来说明 Alfonse 在这里的具体设想吗?

I have played a lot the new Uniform Initialization with {}. Like this:

vector<int> x = {1,2,3,4};
map<int,string> getMap() {
    return { {1,"hello"}, {2,"you"} };
}

It is undisputed that this initialization may change we program C++.
But I wonder if I missed some of the magic possibilities when reading Alfonses's question in the Herb Sutter FAQs.

Alfonse: Uniform initialization (the use of {} to call constructors when the type being constructed can be deduced) has the potential to radically reduce the quantity of typing necessary to create C++ types. It's the kind of thing, like lambdas, that will change how people write C++ code. [...]

Can someone give me an example of what Alfonse exactly envisions here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

奈何桥上唱咆哮 2024-12-12 00:21:14

我认为他的意思

std::vector<int> x{1, 2, 3, 4};
std::map<int, std::string> y{{1, "hello"}, {2, "you"}};

是这比

std::vector<int> x;
x.push_back(1);
x.push_back(2);
x.push_back(3);
x.push_back(4);
std::map<int, std::string> y;
y.emplace(1, "hello");
y.emplace(2, "you");

I assume he means that

std::vector<int> x{1, 2, 3, 4};
std::map<int, std::string> y{{1, "hello"}, {2, "you"}};

is significantly less typing than

std::vector<int> x;
x.push_back(1);
x.push_back(2);
x.push_back(3);
x.push_back(4);
std::map<int, std::string> y;
y.emplace(1, "hello");
y.emplace(2, "you");
瘫痪情歌 2024-12-12 00:21:14

为什么你不认为这是一个简单错误的可能性?也就是说,当他的意思是“创建 C++ 对象”时,他写了“创建 C++ 类型”。奇怪的是,人们不会立即想到:“哦,他的意思是‘物体’,但写错了。”

Why do you discount the possibility that this was a simple mistake? That is, he wrote "create C++ types" when he meant "create C++ object". It seems strange that one wouldn't immediately think, "Oh, he meant 'object' but wrote the wrong thing."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文