0

I have code that I have taken from another source. The rest of the code works great. I am trying to append to a tuple using the following code:

// Because std::make_tuple can't be passed
// to higher order functions.
constexpr struct MakeTuple
{
    template< class ...X >
    constexpr std::tuple<X...> operator () ( X ...x ) {
        return std::tuple<X...>( std::move(x)... );
    }
} tuple{};

constexpr struct PushFront
{
    template< class ...X, class Y >
    constexpr auto operator () ( std::tuple<X...> t, Y y )
        -> std::tuple< Y, X... >
    {
        return std::tuple_cat( tuple(std::move(y)), std::move(t) );
    }
} pushFront{};

template <template <typename...> class T, typename... Args, typename... Obs>
T<Obs...> MakeSubject(std::tuple<Obs ...> &&obs, Args&& ... args)
{
    return T<Obs...>(std::move(obs), args...);
}

template <template <typename...> class T, typename... Args, typename... Obs>
std::tuple<T<Obs...>> Store(std::tuple<Obs ...> &&obs, Args&& ... args)
{
    return std::make_tuple(T<Obs...>(std::move(obs), args...));
}

template <typename Base> class Observer
{
}

class Printer : public Observer<Printer>
{
}

template <typename T, typename... Obs> class Subject
{
private:
    std::tuple<Obs &...> observers;
}

template <typename... Obs>
class Pressure : public Subject<Pressure<Obs...>, Obs...> 
{
}

std::ostream& operator << (std::ostream& out, const Printer& ac)
{
    //stuff

    return out;
}

I have code outside a loop like this:

const Printer sentinel; 
auto store = Store<Pressure>(std::move(std::tuple<Printer>(sentinel)), fakePressure); // The first one is just a delimiter

The problem is that in a loop, when I try to append to store tuples by saying:

while(true) // A Demo loop
{
    auto subject = MakeSubject<Pressure>(std::move(obs), q);
    pushFront(store, subject.Observers()));
    std::cout << store; // Always empty
    std::cout << pushFront(store, subject.Observers()); // This works and shows whatever I passed in, but the list of tuples doesn't grow from previous appends.
}

store doesn't grow by appending more and more std::tuples. I expect the semantics of pushFront for tuples to be similar to push_back for std::vector etc.

Any suggestions?

Ivan
  • 7,448
  • 14
  • 69
  • 134

1 Answers1

1

PushFront::operator() returns new tuple with the appended item followed by the items in given tuple. It does not append to the one passed in.

It is not possible to push into the existing one, because a tuple of N+1 elements is a different C++ type than a tuple of N elements.

Krizz
  • 11,362
  • 1
  • 30
  • 43