Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

c++ - Operator overloading for lambdas?

I have asked a similar question before overloading operator >> for lambdas
But i did not explained what i really wanted .

I am writing a simple wrapper around sqlite3 C api .
this is my project on github => sqlite modern cpp

I want to overload the >> operator for lambdas.
I want the fallowing code to work :

database db("dbfile.db");
db << "select age,name,weight from user where age > ? ;"
   << 18
   >> [&](int age, string name, double weight) {
       cout << age << ' ' << name << ' ' << weight << endl;
   };

I want the idea! that is why i abstracted the question in my previous question. I have a database_bind class which is returned by the '<<' operator , i want to be able to overload >> operator on database_bind class for lambdas with different number of arguments.

Currently i'm supporting this syntax :

db << "select age,name,weight from user where age > ? ;"
   << 18
   >> function<void(int,string,double)>([&](int age, string name, double weight) {
       cout << age << ' ' << name << ' ' << weight << endl;
   });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you need is a retrospective cast. A way to compose a correct function object type from passing it only a lambda (and nothing else, no template arguments, not return type specification).

A way to do it without dependencies from other libraries would be the following

#include <iostream>
#include<functional>
#include<vector>


using namespace std;


template<typename T>
struct memfun_type 
{
    using type = void;
};

template<typename Ret, typename Class, typename... Args>
struct memfun_type<Ret(Class::*)(Args...) const>
{
    using type = std::function<Ret(Args...)>;
};

template<typename F>
typename memfun_type<decltype(&F::operator())>::type
FFL(F const &func) 
{ // Function from lambda !
    return func;
}

Then you can be aware of your lambas' return type and write the following

int main() 
{
    database_bind dbb;

    dbb >> FFL([](int i, string s) { cout << i << ' ' << s << endl; });
    dbb >> FFL([](int i) { cout << i << endl; });
    dbb >> FFL([](string s,double d) { cout << s << ' ' << d << endl; });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...