Update3: please go to overloading operators for lamdas
I want to overload operator>>
for lambdas in c++11/14 .
Here is a simple code:
#include<iostream>
#include<functional>
#include<vector>
using namespace std;
template <typename R,typename T>
void operator >> (vector<T>& v, function<R(T)> f){
for(auto& e : v)
f(e);
}
int main(){
vector<int> v = { 1,2,3,4,5,6,7};
auto l = [](int i) { cout << i*i << endl; };
v >> function<void(int)>(l);
}
But what I really want is this:
v >> l; //(I)
v >> [](int i) { cout << i*i << endl; }; //(II)
And get rid of function<F>
.
I have got some ideas from a similar question How to overload an operator for composition of functionals in C++0x?
Especially this code from the second answer overloads the >>
operator for two lambdas.
#include <iostream>
template <class LAMBDA, class ARG>
auto apply(LAMBDA&& l, ARG&& arg) -> decltype(l(arg))
{
return l(arg);
}
template <class LAMBDA1, class LAMBDA2>
class compose_class
{
public:
LAMBDA1 l1;
LAMBDA2 l2;
template <class ARG>
auto operator()(ARG&& arg) ->
decltype(apply(l2, apply(l1, std::forward<ARG>(arg))))
{ return apply(l2, apply(l1, std::forward<ARG>(arg))); }
compose_class(LAMBDA1&& l1, LAMBDA2&& l2)
: l1(std::forward<LAMBDA1>(l1)),l2(std::forward<LAMBDA2>(l2)) {}
};
template <class LAMBDA1, class LAMBDA2>
auto operator>>(LAMBDA1&& l1, LAMBDA2&& l2) ->compose_class<LAMBDA1, LAMBDA2>
{
return compose_class<LAMBDA1, LAMBDA2>
(std::forward<LAMBDA1>(l1), std::forward<LAMBDA2>(l2));
}
int main()
{
auto l1 = [](int i) { return i + 2; };
auto l2 = [](int i) { return i * i; };
std::cout << (l1 >> l2)(3) << std::endl;
}
But I still can't find out how to overload the >>
operator for my simple example.
Update: I actually want to be able to overload the '>>' operator for different lambdas with different number of arguments .
v >> [](int i) { } // calls the overload with one lambda argument
v >> [](int i1,int i2) { } // calls another overload with two lambda arguments
Update2: I think i did not explained what i really wanted , i have asked a new question operator overloading for lambdas?
I have explained the problem with details in that question.