使用 boost 创建一个始终返回 true 的 lambda 函数

发布于 2024-09-15 10:34:18 字数 375 浏览 3 评论 0原文

假设我有一个采用某种形式的谓词的函数:

void Foo( boost::function<bool(int,int,int)> predicate );

如果我想用始终返回 true 的谓词来调用它,我可以定义一个辅助函数:

bool AlwaysTrue( int, int, int ) { return true; }
...
Foo( boost::bind( AlwaysTrue ) );

但是无论如何都可以调用这个函数(可能使用 boost::lambda )而不需要必须定义一个单独的函数吗?

[编辑:忘了说:我不能使用 C++0x]

Suppose I have a function which takes some form of predicate:

void Foo( boost::function<bool(int,int,int)> predicate );

If I want to call it with a predicate that always returns true, I can define a helper function:

bool AlwaysTrue( int, int, int ) { return true; }
...
Foo( boost::bind( AlwaysTrue ) );

But is there anyway to call this function (possibly using boost::lambda) without having to define a separate function?

[Edit: forgot to say: I CAN'T use C++0x]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽你眉间 2024-09-22 10:34:18

UncleBens 在 Scharron 的回答中评论了这一点,但我认为这实际上是最好的答案,所以我偷了它(对不起 UncleBens)。只需使用

Foo(boost::lambda::constant(true));

Boost 文档中所述.Lambda,仅函子的最小数量为零,最大数量无限制。因此传递给函子的任何输入都将被忽略。

UncleBens commented on this in Scharron's answer, but I think it is actually the best answer so I'm stealing it (sorry UncleBens). Simply use

Foo(boost::lambda::constant(true));

As described in the documentation for Boost.Lambda, only the minimum arity of the functor is zero, the maximum arity is unlimited. So any inputs passed to the functor will simply be ignored.

蓝眼睛不忧郁 2024-09-22 10:34:18

这是一个简单的例子:

#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
#include <iostream>

void Foo( boost::function<bool(int,int,int)> predicate )
{
  std::cout << predicate(0, 0, 0) << std::endl;
}

int main()
{
  using namespace boost::lambda;
  Foo(true || (_1 + _2 + _3));
}

诀窍在于 true || (_1 + _2 + _3),您将在其中创建具有 3 个参数的 boost lambda(_1_2_3),始终返回true

Here is a quick example :

#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
#include <iostream>

void Foo( boost::function<bool(int,int,int)> predicate )
{
  std::cout << predicate(0, 0, 0) << std::endl;
}

int main()
{
  using namespace boost::lambda;
  Foo(true || (_1 + _2 + _3));
}

The trick is in true || (_1 + _2 + _3) where you are creating a boost lambda with 3 arguments (_1, _2 and _3), always returning true.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文