October 22, 2024
Chicago 12, Melborne City, USA
templates

Functions chaining with std::tuple


I’m trying to implement functions chain, that get bunch of different functions and member functions at compile time and execute them one by one and stop execution if processing function fails.
It may be any count of functions.
Now I’m stuck on the fact that std::tuple::get doesn’t accept counted variable as template parameter.
How can I implement something like this?

#include <tuple>
#include <stdlib.h>

template<class...Fs>
class Functions
{
public:
    Functions(Fs...functions)
        : m_functions(functions...)
    {
    }

    template<class Arg>
    void operator()(Arg&& arg)
    {
        CallAll<sizeof...(Fs)>(std::forward<Arg>(arg));
    }

private:
    std::tuple<Fs...> m_functions;

    template<size_t index, class Arg>
    decltype(auto) CallSingle(Arg&& arg)
    {
        return std::get<index>(m_functions)(arg);
    }


    template<size_t index, class Arg>
    void CallAll(Arg&& arg)
    {
        while (index != 0) {
            auto ret = CallSingle<index - 1>(std::forward<Arg>(arg));
            if (std::is_same<decltype(ret), bool>()) {
                if (!ret)
                    return;
            }
            index--; // error!
        }
    }
};

int main(int argc, char *argv[])
{
    Functions f{
        [](int x) { return x + 1; },
        [](int x) { return false; },
        [](int x) { return x + 3; }
    };

    f(42);
    return 0;
}

Compile error:

../../main.cpp: In member function 'void Functions<Fs>::CallAll(Arg&&)':
../../main.cpp:90:18: error: decrement of read-only location 'index'
   90 |             index--;
      |                  ^~
../../main.cpp:90:18: error: lvalue required as decrement operand



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video