c++ - 在 boost::lambda 中表达 _1.second->pair().first == r

标签 c++ boost boost-lambda

我有一个表达式需要放入 std::transform作为回调,但我不想为其编写另一个方法。我想表达_1.second->pair().first == rboost::lambda假设_1是传递给它的唯一类型为 std::pair 的参数

我有一个通用的速记仿函数 util::shorthand::pair_secondutil::shorthand::pair_first它返回一对中的第二个和第一个项目。

我可以boost::bind(util::shorthand::pair_second, _1)但接下来做什么呢?如何实现表达式的其余部分?

-1.second模板化类型为 Connection<T> .我无法使用C++11

最佳答案

看看Boost.Lambda bind expressions 。您可以使用它们来绑定(bind)成员函数和成员数据。

关于您正在使用的类型,我没有足够的信息,但类似这样的内容应该有效:

bind(&std::pair<S, R>::first,
     bind(&Connection<T>::pair,
          bind(&std::pair<U, Connection<T> >::second, _1))) == r

注意:此示例中的 bindboost::lambda 命名空间中的,而不是 Boost.Bind。

编辑:完整的、可编译的示例:

#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>

// http://stackoverflow.com/questions/12026884/expressing-1-second-pair-first-r-in-boostlambda/

typedef int S;
typedef int R;

template <typename T>
struct Connection
{
    std::pair<S, R> pair() const {
        return std::make_pair(0, 0);
    }
};

int main()
{
    using namespace boost::lambda;

    typedef int T;
    typedef int U;

    std::vector<std::pair<U, Connection<T> > > vec;
    vec.push_back(std::make_pair(3, Connection<T>()));
    std::vector<bool> res(vec.size());

    int r = 0;
    std::transform(vec.begin(), vec.end(), res.begin(),
        bind(&std::pair<S, R>::first,
            bind(&Connection<T>::pair,
                bind(&std::pair<U, Connection<T> >::second, _1))) == r);

    std::vector<bool>::iterator it, end = res.end();
    for (it = res.begin(); it != end; ++it) {
        std::cout << ' ' << *it;
    }
    std::cout << std::endl;
}

关于c++ - 在 boost::lambda 中表达 _1.second->pair().first == r,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12026884/

相关文章:

c++ - 这个 boost::lambda 使用有什么问题?

c++ - 解释 valgrind 错误

C++11 可变参数模板模板参数

c++ - 创建树数据结构 - 不同的方法

c++ - boost 属性树 : how to store pointers in it?

c++ - boost::mp11::mp_with_index 与 std::function 数组的性能比较

c++ - Boost::Log 使用具有多个接收器的相同后端的安全性

c++ - 如何在我的发布 EXE 中使用 BCGControlBar 调试 DLL

C++ boost::lambda::ret 等价于 phoenix

c++ - 使用 boost lambda 访问静态成员