C++11:make_tuple

翻译来自:https://thispointer.com/c11-make_tuple-tutorial-example/

本文中,我们将讨论什么是 std::make_tuple 以及我们为什么需要它。

初始化一个 std::tuple

我们可以通过在构造函数中传递元素作为参数来初始化一个 std::tuple ,即

// 创建和初始化一个元组
std::tuple < int , double , std::string > result1 { 22, 19.28 , "text" } ;

您可能已经观察到我们需要在元组中将参数类型指定为模板参数。如果元素数量更多,有时会很痛苦。

有了这个,就没有办法自动推断它们,即以下代码将给出编译错误即

// Compile error, as no way to deduce the types of elements in tuple
auto result { 22, 19.28, "text" }; // Compile error
error: unable to deduce ‘std::initializer_list<_Tp>’ from ‘{22, 1.9280000000000001e+1, "text"}’
auto result { 22, 19.28, "text" };

但是 c++11 提供了一些可以帮助我们避免这种痛苦的东西,即std::make_tuple。

std::make_tuple

std::make_tuple 通过从参数类型推导出 tuple 中元素的目标类型来创建一个 std::tuple 对象。

让我们通过一个例子来理解,

// 使用 std::make_tuple 创建一个元组
auto result2 = std:: make_tuple ( 7, 9.8 , "text" ) ;

这里我们没有指定 std::tuple 对象结果封装的任何类型的元素。

std::make_tuple 做了以下事情,

std::make_tuple接受三个参数并自动推导出它们的类型为 int、double 和 string。然后它在内部创建了一个 std::tuple 对象并初始化它并返回它。

// Creating a tuple using std::make_tuple
auto result = std::make_tuple( 7, 9.8, "text" );

因此,基本上 std::make_tuple 有助于自动推导元组类型。

完整的例子如下

#include <iostream>
#include <tuple>
#include <string>
int main()
{
    // Creating and Initializing a tuple
    std::tuple<int, double, std::string> result1 { 22, 19.28, "text" };
    // Compile error, as no way to deduce the types of elements in tuple
    //auto result { 22, 19.28, "text" }; // Compile error
    // Creating a tuple using std::make_tuple
    auto result2 = std::make_tuple( 7, 9.8, "text" );
    // std::make_tuple automatically deduced the type and created tuple
    // Print values
    std::cout << "int value = " << std::get < 0 > (result2) << std::endl;
    std::cout << "double value = " << std::get < 1 > (result2) << std::endl;
    std::cout << "string value = " << std::get < 2 > (result2) << std::endl;
    return 0;
}

C++11:make_tuple

原文链接: https://www.cnblogs.com/Galesaur-wcy/p/15589983.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/215009

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 上午2:38
下一篇 2023年2月13日 上午2:38

相关推荐