4
是否有任何標準select1st
和select2st
相當於C++11
?
看來,這些已被定義只有在GNU CPP。標準select1st和select2nd
是否有任何標準select1st
和select2st
相當於C++11
?
看來,這些已被定義只有在GNU CPP。標準select1st和select2nd
對於C++ 11,可以使用std::bind
像這樣:
auto select1st = std::bind(&std::pair<int, int>::first, std::placeholders::_1);
作出上述函數模板:
#define AUTO_RETURN(...) -> decltype(__VA_ARGS__) {return (__VA_ARGS__);}
template <typename Pair>
auto select1st() AUTO_RETURN(std::bind(&Pair::first, std::placeholders::_1))
另一種方法是一個lambda - 在我看來好得多,但在C++ 11中不是非常通用的:
// the lambda version:
auto select1st = [] (std::pair<int, int> const& pair) {return pair.first; };
使用C++ 14,我們可以使用多態。
auto select1st = [] (auto const& pair) {return pair.first; };
或者,如果你特別喜歡完美轉發語義,
auto select1st = [] (auto&& pair) -> decltype(auto) {
return std::forward<decltype(pair)>(pair).first;
};
有['的std :: bind1st()'](http://www.cplusplus.com/reference/std/functional/bind1st /)和['std :: bind2nd()'](http://www.cplusplus.com/reference/std/functional/bind2nd/),但在C++ 11中,您只需要[ '的std ::綁定()'](http://en.cppreference.com/w/cpp/utility/functional/bind)。 – 0x499602D2 2014-10-04 18:58:12
@ 0x499602D2,在C++ 14中有多態的lambda,它在各方面都優越。我猜'std :: bind'是短命的「青銅時代」(C++ 11)的一部分。我們現在擁有更好的工具;-) – TemplateRex 2014-10-05 08:10:57