For-loop with conditional call of a variadic amount of functions

Instead of performing recursive calls, I want an arbitrary number of functions to trigger based on some condition in a loop:

template <typename method0, typename method1, typename ... Args>
void loop(Args ... args)
{
    for (int i = 0; i < iter_max; i++)
    {
        if (method0::condition(args))
        {
            args = method0::call(args);
        }
        if (method1::condition(args))
        {
            args = method1::call(args);
        }
        //...
    }
}

How do I transform method0, method1 to be called for a variadic number of typename ... methods?

>Solution :

I am not sure if I understand the question. Especially I am not sure if condition and call are themself variadic. I assume not and given this two types (or more):

struct A {
    static bool condition(int x) { 
        std::cout << "A::condition " << x << "\n";
        return true;
    }
    static int call(int) { 
        std::cout << "A::call\n";
        return 42;
    }
};
struct B {
    static bool condition(int x) { 
        std::cout << "B::condition " << x << "\n";
        return false;
    }
    static int call(int) { 
        std::cout << "B::call\n";
        return 0;
    }
};

You can make loop call n-th types condition and call with n-th args like this:

template <typename... Methods, typename ... Args>
void loop(Args ... args)
{
    int iter_max = 2;
    auto apply = []<typename m>(auto& a){
        if (m::condition(a)) a = m::call(a); 
    };
    (apply.template operator()<Methods>(args), ...);
}


int main() {
    loop<A,B>(1,2);
}

Output:

A::condition 1
A::call
B::condition 2

Leave a Reply