【问题标题】:C++: conjunction of binds?C++:绑定的结合?
【发布时间】:2010-04-14 15:35:36
【问题描述】:

假设有以下两个函数:

#include <iostream>
#include <cstdlib> // atoi
#include <cstring> // strcmp
#include <boost/bind.hpp>

bool match1(const char* a, const char* b) {
    return (strcmp(a, b) == 0);
}

bool match2(int a, const char* b) {
    return (atoi(b) == a);
}

这些函数中的每一个都接受两个参数,但可以通过使用 (std/boost)bind 将其转换为只接受一个参数的可调用对象。大致如下:

boost::bind(match1, "a test");
boost::bind(match2, 42);

我希望能够从像这样的两个接受一个参数并返回 bool 的函数中获取一个可调用对象,该对象接受两个参数并返回 bools 的 && .参数的类型是任意的。

对于返回 bool 的函数,类似于 operator&amp;&amp;

【问题讨论】:

  • 你不想要一个接受一个参数并返回一个 bool 的函数吗?即相当于match1("a test", X) &amp;&amp; match2(42, X)?还是你真的想要match1("a test", X) &amp;&amp; match2(42, Y)
  • 我真的想要一个带有两个参数的函数。

标签: c++ boost bind


【解决方案1】:

boost::bind 的返回类型重载了operator &amp;&amp;(以及many others)。所以你可以写

boost::bind(match1, "a test", _1) && boost::bind(match2, 42, _2);

如果要存储此值,请使用boost::function。在这种情况下,类型将是

boost::function<bool(const char *, const char *)>

请注意,这不是 boost::bind 的返回类型(未指定),但任何具有正确签名的函子都可以转换为 boost::function

【讨论】:

  • 我可以有一个返回boost:bind类型的函数吗?
  • 它可以工作gist.github.com/367475(顺便说一句,为什么_1_2 在全局命名空间中?)
  • @Sebastian,因为它更容易使用? (仅供参考,它们位于boost/bind/placeholders.hpp 中定义的未命名命名空间中。)
  • @Jesse Beder:Lambda 使用 boost::lambda 而 Phoenix 使用 boost::spirit 命名空间作为占位符,所以不清楚为什么 Bind 库应该有所不同。
  • @Sebastian,这似乎是一个热门问题。我在 boost 邮件列表中找到了这个对话:lists.boost.org/boost-users/2009/06/48805.php 链接到一张票,但看起来并没有做任何事情。并且似乎std::bind 的占位符将在std::placeholder 中。
猜你喜欢
  • 2013-02-05
  • 1970-01-01
  • 2018-04-06
  • 2011-02-02
  • 2018-06-12
  • 2018-03-23
  • 1970-01-01
  • 1970-01-01
  • 2015-04-27
相关资源
最近更新 更多