传递条件作为参数 [英] Passing condition as parameter

查看:155
本文介绍了传递条件作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先要解释我要做什么:

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

void Foo(int &num, bool condition);

Foo(x, x > 3);

此代码基本上会在调用函数之前计算条件的bool,然后传递纯true或false 。我正在寻找一种方法让它通过条件本身,所以我可以做这样的事情:

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.

提前感谢

推荐答案

使用标准库的示例函子

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

请参阅 < functional> 。C ++已经为你提供了out-

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

如果您的编译器有足够的支持(例如GCC 4.5或VC10),您还可以访问 lambda函数。例如。使用与上述相同的 func()

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

这篇关于传递条件作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆