Home > Mobile >  Overload pattern as a storage
Overload pattern as a storage

Time:07-01

I am trying to use overload pattern as a storage, but I am having trouble appending a new element.

Is it actually possible?

There is an example - https://godbolt.org/z/ohvY4sx9q

PS stackoverflow doesn't allow to paste that much code

template<typename... Ts>
struct Container : Ts...
{
    template <typename H>
    auto append(H h) { return Container<Ts..., H> { ( static_cast<Ts>(*this),... ), h }; }
};

CodePudding user response:

godbolt Is this what you want?

#include <iostream>
#include <typeinfo>

template<typename... Ts>
struct Container : Ts...
{
    void operator()(auto&&... args)
    {
        ( [&]() {
          std::cout << "type => " << typeid(Ts).name() << std::endl;
          Ts::operator()(std::forward<decltype(args)>(args)...);
        }(), ... );
    }

    // here just return your new container with appended type
    template <typename H>
    auto append(H h) { return Container<Ts..., H> {}; }
};
template<class... Ts> Container(Ts...) -> Container<Ts...>;



int main()
{
    auto foo = Container {
        []() { std::cout << "1" << std::endl; },
        []() { std::cout << "2" << std::endl; },
    };

    foo();

    auto bar = foo.append([]() { std::cout << "3" << std::endl; });
    bar();
}
  •  Tags:  
  • c
  • Related