C/C++教程

C++11:make_tuple

本文主要是介绍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<int, double, std::string> 对象并初始化它并返回它。

// 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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!