简体   繁体   English

如何从对象std :: tuple获取对元组尾部的引用<Head,Tail…>

[英]How to get a reference to the tail of a tuple from an object std::tuple<Head,Tail…>

I have defined: 我定义了:

template<class Head,class ...Tail>
struct elem{
    std::tuple<Head,Tail...> dm;
};

I have the functions head(), tail() and others for the class elem, but they create copies, they return a copy of the head of tuple or the tail of tuple, but I need a reference to the tail of this->dm. 我有elem类的函数head(),tail()和其他函数,但是它们创建了副本,它们返回元组的头部或元组的尾部的副本,但是我需要引用this->的尾部DM。

For the head is easy, std::get<0>(this->dm) give me the reference. 因为头很容易,所以std::get<0>(this->dm)给我参考。

Is it possible for the tail? 尾巴有可能吗? By tail, I mean all the elements after the first one. 尾巴,是指第一个元素之后的所有元素。

Such a thing would only be possible if a tuple<A, B, C> were stored internally as something equivalent to a cons cell: 仅当tuple<A, B, C>在内部存储为等同于cons单元格的东西时tuple<A, B, C>此类事情才有可能:

struct __tuple_A_B_C {
    A car;
    tuple<B, C> cdr;

    A& head() { return car; }
    tuple<B, C>& tail() { return cdr; }
};

But that isn't the case - all you know is that you have subobjects of types A , B , and C . 但这不是事实-您所知道的是您具有类型ABC子对象。 Their layout is completely unspecified - and you definitely don't know whether or not implementations use recursion like this to implement tuple . 它们的布局是完全不确定的-并且您绝对不知道实现是否使用像这样的递归来实现tuple They're allowed to, but I'm not sure any do. 他们被允许,但我不确定有什么办法。

The best you could do is, given a tuple<A, B, C> return a tuple<B&, C&> . 最好的办法是给定一个tuple<A, B, C>返回一个tuple<B&, C&> In C++17, that's not so bad to implement: 在C ++ 17中,实现起来并不难:

template<class Head,class ...Tail>
struct elem{
    std::tuple<Head,Tail...> dm;

    auto tail() {
        return std::apply([](auto&, auto&... rest){
            return std::tie(rest...);
        }, dm);
    }
};

But if you really want this recursive cons-cell-like approach, you're probably better off actually implementing your own recursion so you get the desired behavior: 但是,如果您真的想要这种类似于cons-cell的递归方法,那么最好实际实现自己的递归,这样您就可以得到所需的行为:

template <class Head, class... Tail>
struct elem {
    Head head;
    elem<Tail...> tail;
};

template <class Head>
struct elem<Head> {
    Head head;
};

Depends on what you're actually doing. 取决于您的实际操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM