C++函數對象(也稱為仿函數或functor)是一種可以像函數一樣被調用的對象
std::vector<int> vec = {3, 1, 4, 1, 5, 9};
std::sort(vec.begin(), vec.end(), [](int a, int b) { return a < b; }); // 使用lambda表達式作為函數對象
class Button {
public:
void onClick(std::function<void()> callback) {
// 當按鈕被點擊時,調用回調函數
callback();
}
};
Button button;
button.onClick([]() {
std::cout << "Button clicked!" << std::endl;
}); // 使用lambda表達式作為回調函數
class Counter {
public:
int getValue() const { return value_; }
void setValue(int value) { value_ = value; }
private:
int value_ = 0;
};
class CounterAdapter {
public:
CounterAdapter(Counter& counter) : counter_(counter) {}
int getValue() const { return counter_.getValue(); }
void increment() { counter_.setValue(counter_.getValue() + 1); }
private:
Counter& counter_;
};
Counter counter;
CounterAdapter adapter(counter);
std::cout << "Value: " << adapter.getValue() << std::endl; // 使用CounterAdapter適配器
adapter.increment();
std::cout << "Value after increment: " << adapter.getValue() << std::endl;
class Logger {
public:
void log(const std::string& message) const {
std::cout << "Log: " << message << std::endl;
}
};
class LoggingDecorator {
public:
LoggingDecorator(std::ostream& os, const std::string& prefix) : os_(os), prefix_(prefix) {}
template <typename T>
void log(const T& message) const {
os_ << prefix_ << message << std::endl;
}
private:
std::ostream& os_;
std::string prefix_;
};
std::cout << "Before logging" << std::endl;
LoggingDecorator logger(std::cout, "Info: ");
logger.log("Hello, World!"); // 使用LoggingDecorator裝飾器
std::cout << "After logging" << std::endl;
總之,C++函數對象在許多場景中都非常有用,它們提供了一種靈活的方式來封裝和傳遞行為。