如何通过相同的参数初始化所有元组元素? [英] How to initialize all tuple elements by the same arguments?

查看:96
本文介绍了如何通过相同的参数初始化所有元组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用基础类型的非默认构造函数通过相同的参数初始化 std :: tuple 的所有元素?

Is it possible to initialize all elements of std::tuple by the same argument, using the non-default constructors of the underlying types?

template <typename... TElements>
struct Container {
    // I'd wish to be able to do something like this:
    Container(Foo foo, Bar bar)
        : tuple(foo, bar)
    {}
    std::tuple<TElements...> tuple;
};

要点是,我不知道元组的大小(由可变参数作为模板),因此我无法根据需要多次重复参数。我唯一知道的是 TElements 中的所有类型都有一个构造函数,该构造函数使用 Foo Bar 作为参数,并且没有默认的构造函数。

The point is that I don't know the tuple size (it's templated by a variadic parameter), so I can't duplicate the arguments as many times as I need. The only thing I know is that all types in TElements have a constructor taking Foo and Bar as arguments and don't have a default constructor.

推荐答案

最清晰的方法就是构造元组构造函数参数列表中的每个元素:

The clearest way is just to construct each element in the tuple constructor argument list:

template <typename... TElements>
struct Container {
    Container(Foo foo, Bar bar)
        : tuple(TElements{foo, bar}...)
    {}
    std::tuple<TElements...> tuple;
};

这将导致移动(或复制)从其对应的构造函数参数构造元组的每个元素;如果无法接受,则可以使用分段构造:

This will result in move (or copy) constructing each element of the tuple from its corresponding constructor parameter; if this is unacceptable you could use piecewise construction:

template <typename... TElements>
struct Container {
    Container(Foo foo, Bar bar)
        : tuple(std::piecewise_construct, (sizeof(TElements), std::tie(foo, bar))...)
    {}
    std::tuple<TElements...> tuple;
};

不幸的是,在这种情况下,我们必须进行某种形式的体操(此处 sizeof 和逗号运算符)来获取可变参数列表 TElements 并被忽略。

Unfortunately in this case we have to do some kind of gymnastics (here sizeof and a comma operator) to get the variadic list TElements mentioned and ignored.

这篇关于如何通过相同的参数初始化所有元组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆