Function Object(函數對象)是否僅能作為 sort 等演算法的比較參數?使用 bind1st 綁定後,能否直接拿來與單一數值比較?
可以直接調用。綁定後的函數對象本質上是一個可呼叫實體,擁有 operator(),可像普通函數一樣傳入參數執行。例如:
std::binder1st<std::greater<int>> fn = std::bind1st(std::greater<int>(), 10);
bool result = fn(5); // 相當於 10 > 5,返回 true
雖然語法合法,但實際開發中極少這樣使用。現代 C++(C++11 起)推薦使用 std::bind 或 Lambda 表達式,語法更清晰、泛型支援更好:
// C++11 Lambda
auto fn = [](int x){ return 10 > x; };
bool result = fn(5);
// std::bind
auto fn2 = std::bind(std::greater<int>(), 10, std::placeholders::_1);
bool result2 = fn2(5);
bind1st/bind2nd 已在 C++11 中棄用,C++17 移除,請遷移至新標準。