A C++ pattern where you create a temporary object and immediately call its function operator in
one line. The syntax Class<Template>{constructor_args}(function_args) creates an object, uses
it, then destroys it automatically.
Simple Usage Example
.
#include <iostream>
#include <vector>
// A simple function object that adds a value to each element
template<typename T>
class AddValue {
private:
T value;
public:
AddValue(T val) : value(val) {}
void operator()(std::vector<T>& arr) {
for(auto& x : arr) {
x += value;
}
}
};
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Pattern: Class<Template>{args}(target)
AddValue<int>{10}(numbers); // Add 10 to each element
// Print result
for(int x : numbers) {
std::cout << x << " "; // Output: 11 12 13 14 15
}
return 0;
}
..
This pattern is commonly used in libraries for one-time operations like filling arrays, applying
transformations, or configuring objects without creating persistent variables.
Thank you! ππ»♂️
No comments:
Post a Comment