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

C++11: How is boost::make_tuple different from std::make_tuple?

本文关键字:make tuple 何不同 std C++11 boost      更新时间:2023-10-16

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。

那么我缺少任何细微差别吗?

没有功能差异。

boost::tuple创建于近二十年前,std::tuple于 2011 年 C++11 年引入核心标准库,距今仅 6 年。

对于术语"可互换"的给定定义,它们不是"可互换的"。不能将std::tuple<>分配给boost::tuple<>,反之亦然,因为即使它们的实现相同,它们仍然表示不同的对象。

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

编辑:

正如@Nir所指出的,boost::tuplestd::tuple之间有一些语法差异,特别是涉及get<>()语法,这也是boost::tuple的成员函数,并且只是std::tuple的自由函数。