我有一个表达式需要放入 std::transform
作为回调,但我不想为其编写另一个方法。我想表达_1.second->pair().first == r
至boost::lambda
假设_1
是传递给它的唯一类型为 std::pair
的参数
我有一个通用的速记仿函数 util::shorthand::pair_second
和util::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
注意:此示例中的 bind
是 boost::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/