I'm trying to figure out how to generically overload the operator|()
for a given base class object to serialize or chain function calls that are similar to how pipes
or operator<<()
works... I'd like to chain them through the pipe operator... This way I can have a series of standalone functions, and call them on a single data object... In other words, to perform multiple transformations on the same data type, like in a streaming system...
Consider the following pseudo code sample: this code probably won't compile, I don't have my compiler handy and I may be using the wrong syntax for the function pointers or function objects as a parameter in the operators... This is only to illustrate the pattern and behavior that I'm after.
template<typename T>
typedef T(*Func)(T); // Function Pointer for functors-lambdas-etc...
template<typename T>
struct pipe_object {
T operator|(T(*Func)(T) func) {
return func(T);
}
T operator()(T(*Func)(T) func) {
return this->operator|(t, func);
}
};
Then I might want to use them something like this:
constexpr int add_one_f(int x) {
return (x+1);
}
constexpr int add_two_f(int x) {
return (x+2);
}
void foo() {
pipe_object<int> p1 = {};
pipe_object<int> p2 = {};
int result = p1(&add_one) | p2(&add_two);
// or something like...
int result = p1 | p2; // ... etc ...
// or something like:
p1 = add_one | add_two | p2; // ... etc ...
}
I just don't know how to propagate the intput
- output
in the |()
operator... Would I have to overload two versions so that it can recognize |(lhs, rhs)
as well as |(rhs, lhs)
?
More than just that, what if I want to expand this so that my functors
or lambdas
were to take multiple arguments...
I've been doing Google searches on this and only found a couple of resources but nothing that is concrete, simple, elegant, and up to date at least with C++17 features...
If you know of any good source materials on this subject please let me know!
See Question&Answers more detail:os