2017-10-04 48 views
0

http://en.cppreference.com/w/cpp/utility/tuple/make_tuple (爲了方便代碼粘貼)C++ 11:boost :: make_tuple與std :: make_tuple有什麼不同?

#include <iostream> 
#include <tuple> 
#include <functional> 

std::tuple<int, int> f() // this function returns multiple values 
{ 
    int x = 5; 
    return std::make_tuple(x, 7); // return {x,7}; in C++17 
} 

int main() 
{ 
    // heterogeneous tuple construction 
    int n = 1; 
    auto t = std::make_tuple(10, "Test", 3.14, std::ref(n), n); 
    n = 7; 
    std::cout << "The value of t is " << "(" 
       << std::get<0>(t) << ", " << std::get<1>(t) << ", " 
       << std::get<2>(t) << ", " << std::get<3>(t) << ", " 
       << std::get<4>(t) << ")\n"; 

    // function returning multiple values 
    int a, b; 
    std::tie(a, b) = f(); 
    std::cout << a << " " << b << "\n"; 
} 

https://theboostcpplibraries.com/boost.tuple

#include <boost/tuple/tuple.hpp> 
#include <boost/tuple/tuple_io.hpp> 
#include <string> 
#include <iostream> 

int main() 
{ 
    typedef boost::tuple<std::string, int, bool> animal; 
    animal a = boost::make_tuple("cat", 4, true); 
    a.get<0>() = "dog"; 
    std::cout << std::boolalpha << a << '\n'; 
} 

這似乎是基於增強的文檔:: make_tuple和std :: make_tuple上是完全可以互換的。

它們真的可以互換嗎?他們在什麼情況下不是?

在升壓文檔上面說的boost ::元組和std ::元組是在C++ 11

在STD文檔一樣,它說make_tuple返回一個std ::元組。

那麼有沒有我失蹤的細微差別?

+1

我認爲C++ 11幾乎只採用了boost :: tuple。所以他們會一樣也不奇怪。 –

回答

4

沒有功能差異。

boost::tuple創建於近二十年前,2011年僅在6年前,std::tuple被引入到C++ 11的核心標準庫中。

對於術語「可互換」的給定定義,它們不是「可互換的」。您不能將std::tuple<>指定爲boost::tuple<>,反之亦然,因爲即使它們的實現相同,它們仍然代表不同的對象。

但是,因爲它們本質上是相同的,所以您可以執行查找→替換爲boost::tuplestd::tuple,並且或多或少都具有相同的行爲和執行代碼,並且因爲依賴boost庫並不是每個程序員可以有,幾乎普遍建議任何有權訪問> = C++ 11的項目都喜歡std::tuple

編輯:

正如@Nir指出的那樣,有boost::tuplestd::tuple之間幾個語法差異,特別是涉及get<>()語法,這也是boost::tuple一個成員函數並且僅用於std::tuple自由功能。

+3

boost和std元組之間的一個非常大的區別是boost元組有一個'get'成員函數,這實際上可能是它最常用的方法。 std'get'只提供一個免費函數,所以你提出的重構可能會嚴重破壞大部分代碼庫。 –

+0

「沒有功能差異。」這並不完全正確。 'boost :: tuple'的功能更加廣泛,所以你不能指望所有的東西都能用簡單的替換工作。並且你的編輯不是很正確 - 增強提供成員和自由功能,而std只有免費功能。 – Slava

+0

@Slava「*'boost :: tuple'的功能更爲深入*」我不知道你在說什麼。 – Xirema

相關問題