C++ 的 std::bind
可以實現一定程度的函數組合,但并不是特別優雅和靈活。為了實現更簡潔、高效的函數組合,你可以考慮使用 C++11 引入的 lambda 表達式或者 std::bind
結合 std::placeholders
。
下面是一個使用 std::bind
實現函數組合的例子:
#include <iostream>
#include <functional>
int add(int a, int b) {
return a + b;
}
int multiply(int a, int b) {
return a * b;
}
int main() {
auto add_and_multiply = std::bind(add, std::placeholders::_1, std::placeholders::_2) * multiply;
int result = add_and_multiply(3, 4); // 結果為 (3 + 4) * 4 = 28
std::cout << "Result: " << result << std::endl;
return 0;
}
然而,使用 lambda 表達式可以更簡潔地實現函數組合:
#include <iostream>
#include <functional>
int add(int a, int b) {
return a + b;
}
int multiply(int a, int b) {
return a * b;
}
int main() {
auto add_and_multiply = [](int a, int b) { return add(a, b) * multiply(a, b); };
int result = add_and_multiply(3, 4); // 結果為 (3 + 4) * 4 = 28
std::cout << "Result: " << result << std::endl;
return 0;
}
總之,雖然 std::bind
可以實現函數組合,但使用 lambda 表達式會更加簡潔和高效。