Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overload pattern as a storage

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 }; }
};

>Solution :

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading