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++函数对象在许多场景中都非常有用,它们提供了一种灵活的方式来封装和传递行为。