`std :: make_tuple`的原因是什么? [英] What is the reason for `std::make_tuple`?

查看:213
本文介绍了`std :: make_tuple`的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是为什么std::make_tuple存在?我知道在某些情况下该函数会减少您必须键入的字符数量,因为可以避免使用模板参数.但这是唯一原因吗?是什么让std::tuple特别之处在于该函数存在而其他类模板没有该函数呢?仅仅是因为在这种情况下您可能会更频繁地使用std::tuple吗?

I mean why does std::make_tuple exist? I know that there are situations where the function reduces the amount of characters you have to type because you can avoid template parameters. But is it the only reason? What makes std::tuple special that the function exists while other class templates haven't such function? Is it only because you may use std::tuple more often in such situations?

以下是两个示例,其中std::make_tuple减少了字符数量:

Here are two examples where std::make_tuple reduces the amount of characters:

// Avoiding template parameters in definition of variable.
// Consider that template parameters can be very long sometimes.
std::tuple<int, double> t(0, 0.0); // without std::make_tuple
auto t = std::make_tuple(0, 0.0);  // with std::make_tuple

// Avoiding template parameters at construction.
f(std::tuple<int, double>(0, 0.0)); // without std::make_tuple
f(std::make_tuple(0, 0.0));         // with std::make_tuple

但是像上面写的那样,许多其他类模板没有这样的功能.

But like written above, you don't have a function like this for many other class templates.

推荐答案

因为不能对构造函数使用自变量推导.您需要明确编写std::tuple<int, double>(i,d);.

Because you cannot use argument deduction for constructors. You need to write explicitly std::tuple<int, double>(i,d);.

它使创建元组并将其一次传递给另一个函数更加方便.

It makes it more convenient for creating a tuple and passing it to another function in one-shot.

takes_tuple(make_tuple(i,d))takes_tuple(tuple<int,double>(i,d)).

id的类型更改时,尤其是在新旧类型之间可能进行转换的情况下,减少更改的地方.

One less place to change when the type of i or d changes, especially if there were possible conversions to between the old and new types.

如果有可能写std::tuple(i,d);,那么make_*(可能是 )将是多余的.

If it were possible to write std::tuple(i,d);, make_* would (probably) be redundant.

(这里不要问为什么.也许出于类似的原因,语法A a();不调用默认构造函数.有些c ++语法很痛苦.)

(Don't ask why here. Maybe for similar reasons why syntax A a(); does not invoke a default constructor. There are some painful c++ syntax peculiarities.)

更新说明: 正如 Daniel 正确地指出的那样,c ++ 17将得到增强,因此模板参数推导将适用于构造函数,并且这样的授权将变得过时.

UPDATE NOTE: As Daniel rightly notices, c++17 will be enhanced, so that template argument deduction will work for constructors, and such delegation will become obsolete.

这篇关于`std :: make_tuple`的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆