C ++ 11:boost :: make_tuple与std :: make_tuple有什么不同?

时间:2017-10-04 20:11:25

标签: c++ c++11 boost

http://en.cppreference.com/w/cpp/utility/tuple/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';
}

似乎基于文档,boost :: make_tuple和std :: make_tuple完全可以互换。

它们真的可以互换吗?在什么情况下他们不是?

在boost文档中,它表示boost :: tuple和std :: tuple在c ++ 11中是相同的

在std文档中,它说make_tuple返回一个std :: tuple。

那么我有什么细微差别吗?

1 个答案:

答案 0 :(得分:4)

没有功能差异。

boost::tuple是在差不多20年前创建的,std::tuple于2011年在C ++ 11中引入了标准库,仅在6年前。

对于术语“可互换”的给定定义,他们并不是可互换的&#34;。您无法将std::tuple<>分配给boost::tuple<>,反之亦然,因为即使它们的实现相同,它们仍然代表不同的对象。

但是,因为它们本质上是相同的,所以你可以对boost::tuplestd::tuple进行查找→替换,并使用相同的行为和执行代码进行更多或更少的到达,并且因为依赖于提升库不是每个程序员都可以拥有的,几乎普遍建议任何有权访问&gt; = C ++ 11的项目在所有情况下都更喜欢std::tuple

编辑:

正如@Nir所指出的,boost::tuplestd::tuple之间存在一些语法差异,特别是get<>()语法,它也是boost::tuple的成员函数。并且只有std::tuple的免费功能。