我有一个表达式需要放入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;
}