4

我知道我可以使用以下内容:

template <typename Pair> 
struct ComparePairThroughSecond : public std::unary_function<Pair, bool>
{ 
    bool operator ()(const Pair& p1, const Pair& p2) const
    {  
        return p1.second < p2.second; 
    } 
};

std::set<std::pair<int, long>, ComparePairThroughSecond> somevar;

但想知道是否可以使用 boost::bind 来完成

4

2 回答 2

3

下一个怎么样。我正在使用 boost::function 来“擦除”比较器的实际类型。比较器是使用 boost:bind 本身创建的。

  typedef std::pair<int, int> IntPair;
  typedef boost::function<bool (const IntPair &, const IntPair &)> Comparator;
  Comparator c = boost::bind(&IntPair::second, _1) < boost::bind(&IntPair::second, _2);
  std::set<IntPair, Comparator> s(c);

  s.insert(IntPair(5,6));
  s.insert(IntPair(3,4));
  s.insert(IntPair(1,2));
  BOOST_FOREACH(IntPair const & p, s)
  {
    std::cout << p.second;
  }
于 2010-06-03T23:10:43.683 回答
0

问题在于——除非你将代码编写为模板或使用 C++0x 特性——否则你必须命名 boost::bind 表达式的类型。但这些类型通常具有非常复杂的名称。

C++98中的模板参数推导:

template<class Fun>
void main_main(Fun fun) {
   set<pair<int,long>,Fun> s (fun);
   …
}

int main() {
   main_main(…boost::bind(…)…);
}

在 C++0x 中使用 auto 和 decltype:

int main() {
   auto fun = …boost::bind(…)…;
   set<pair<int,long>,decltype(fun)> s (fun);
   main_main(boost::bind(…));
}

至于实际的绑定表达式,我认为是这样的:

typedef std::pair<int,long> pil;
boost::bind(&pil::second,_1) < boost::bind(&pil::second,_2)

(未经测试)

于 2010-06-02T16:57:16.600 回答