使用allocator c ++创建元组

问题描述 投票:0回答:1

我正在学习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)

这怎么称呼?

c++ std stdtuple
1个回答
0
投票

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

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) >= 1std::is_constructible<Ti, Ui&&>::valuetrue都是i,则此重载仅参与重载决策。

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

例如。对于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不参与其构造。见Uses-allocator construction

© www.soinside.com 2019 - 2024. All rights reserved.