Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing condition as parameter

First of all to explain what I'm trying to do:

void Foo(int &num, bool condition);

Foo(x, x > 3);

This code basically would evaluate the bool of the condition before calling the function and then pass pure true or false. I'm looking for a way to make it pass the condition itself, so I could do something like this:

void Foo(int &num, bool condition)
{
    while(!condition)
    {
        num = std::rand();
    }
}

I know there could be a workaround by passing a string containing the condition and parsing the latter, and I'm working on it right now, but I find it rather inefficient way. The accepted answer will be the one explaining the solution on any other way beside the one with parsing the string containing the condition, or an answer that clarifies that this way of passing conditions is impossible.

Thanks in advance

like image 235
Johnny Avatar asked Jul 24 '10 06:07

Johnny


1 Answers

One example using a standard library functor:

#include <functional>

template<class UnaryPred> void func(int& num, UnaryPred predicate) {
    while(!predicate(num)) num = std::rand();
}

void test() {
    int i = 0;
    func(i, std::bind1st(std::greater<int>(), 3));
}

See the documentation on <functional> for what C++ already provides you with out-of-the-box.

If your compiler has sufficient support (e.g. GCC 4.5 or VC10), you can also go for lambda functions. E.g. using the same func() as above:

func(i, [](int num) { return num > 3; });
like image 79
Georg Fritzsche Avatar answered Oct 04 '22 03:10

Georg Fritzsche