Joh*_*nny 5 c++ parameter-passing
首先要解释我正在尝试做什么:
void Foo(int &num, bool condition);
Foo(x, x > 3);
Run Code Online (Sandbox Code Playgroud)
这段代码基本上会在调用函数之前评估条件的bool,然后传递纯true或false.我正在寻找一种方法让它通过条件本身,所以我可以做这样的事情:
void Foo(int &num, bool condition)
{
while(!condition)
{
num = std::rand();
}
}
Run Code Online (Sandbox Code Playgroud)
我知道可以通过传递一个包含条件的字符串并解析后者来解决这个问题,我现在正在研究它,但我觉得它效率很低.接受的答案将是解释除了包含条件的字符串之外的任何其他方式的解决方案,或者澄清这种传递条件的方式是不可能的答案.
提前致谢
Geo*_*che 12
使用标准库仿函数的一个示例:
#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));
}
Run Code Online (Sandbox Code Playgroud)
有关<functional>C++已经为您提供的开箱即用的文档,请参阅文档.
如果您的编译器有足够的支持(例如GCC 4.5或VC10),您也可以使用lambda函数.例如使用与func()上面相同的内容:
func(i, [](int num) { return num > 3; });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4513 次 |
| 最近记录: |