使用分配器 c++ 创建元组

Creating tuple with allocator c++

本文关键字:创建 元组 c++ 分配器      更新时间:2023-10-16

我正在C++中查找元组,现在我正在尝试使用 libcxx 的分配器创建元组

template <class _Alloc>
LIBCPP_INLINE_VISIBILITY
tuple(allocator_arg_t, const _Alloc& __a, const _Tp& ... __t)

例如:

std::allocator<int> myAllocator;
std::tuple<int> t(std::allocator_arg, myAllocator, 2);

但似乎上面的字符串称为

template <class Alloc>
tuple(allocator_arg_t, const Alloc& a, const Types&...);

我应该为此更改什么?

同样,有一行我不清楚:

explicit
tuple(_Up&&... __u)

这怎么叫?

当您查看实现的源代码并查看

namespace std {
// Other things

template <typename ... _Tp>
class tuple {

// More things

template <class _Alloc>
LIBCPP_INLINE_VISIBILITY
tuple(allocator_arg_t, const _Alloc& __a, const _Tp& ... __t)
// an implementation of this constructor

};
}

那是cppreference 命名的构造函数

template <class Alloc>
tuple(allocator_arg_t, const Alloc& a, const Types&...);

您的实现已选择使用保留供其使用的名称。这些名称究竟是什么对编译器来说并不重要。

什么是const _Tp& ... __t

它是要复制到元组中的元素的参数包。对于std::tuple<int>,它是const int&,对于std::tuple<std::string, bool, char>它是const std::string &, const bool &, const char &__t是参数包的名称。C++允许模板具有不同数量的参数。

tuple(_Up&&... __u)呢?

这就是过载 (3)

转换构造函数。使用std::forward<UTypes>(args)中的相应值初始化元组的每个元素。

仅当sizeof...(Types) == sizeof...(UTypes)sizeof...(Types) >= 1并且对所有itruestd::is_constructible<Ti, Ui&&>::value时,此重载才参与过载解决。

构造函数是显式的,当且仅当std::is_convertible<Ui&&, Ti>::value至少false一个i

例如,对于std::tuple<int> tup('a');tup将通过匹配UTypes...char进行初始化,第一个成员的数值为'a'(大多数平台上为97)。

请注意,对std::tuple<int>使用分配器感知构造函数没有多大意义,因为int不是分配器感知类型。这些构造函数存在于以下情况下

using statefully_allocated = std::vector<int, my_stateful_allocator<int>>;
my_stateful_allocator<int> alloc1 = /* something */
statefully_allocated source(alloc);
my_stateful_allocator<int> alloc2 = /* something else */
std::tuple<statefully_allocated, char> tup(std::allocator_arg, alloc2, source, 'a');

其中statefully_allocated成员复制source的内容,但使用alloc2的副本进行分配。char成员只是一个普通的charalloc2参与其构造。请参阅用途分配器构造