我正在学习C ++中的元组,现在我正在尝试使用libc ++中的allocator创建元组
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
和std::is_constructible<Ti, Ui&&>::value
和true
都是i
,则此重载仅参与重载决策。当且仅当
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
成员只是一个普通的char
,alloc2
不参与其构造。见Uses-allocator construction