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

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?

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

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