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;
}

 

 

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM