Skip to content

Commit

Permalink
Merge pull request #42 from aminroosta/functors
Browse files Browse the repository at this point in the history
Fixes #11
  • Loading branch information
aminroosta committed Mar 26, 2016
2 parents 93ccd4e + e03e427 commit 709c4b5
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
21 changes: 21 additions & 0 deletions hdr/sqlite_modern_cpp/utility/function_traits.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,26 @@ namespace sqlite {
static const std::size_t arity = sizeof...(Arguments);
};

/* support the non-const operator ()
* this will work with user defined functors */
template <
typename ClassType,
typename ReturnType,
typename... Arguments
>
struct function_traits<
ReturnType(ClassType::*)(Arguments...)
> {
typedef ReturnType result_type;

template <std::size_t Index>
using argument = typename std::tuple_element<
Index,
std::tuple<Arguments...>
>::type;

static const std::size_t arity = sizeof...(Arguments);
};

}
}
57 changes: 57 additions & 0 deletions tests/functors.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sqlite_modern_cpp.h>

using namespace sqlite;
using namespace std;

struct tbl_functor {
explicit tbl_functor(vector<pair<int, string> > &vec_) : vec(vec_) { }

void operator() ( int id, string name) {
vec.push_back(make_pair(id, move(name)));
}
vector<pair<int,string> > &vec;
};

int main() {

try {
database db(":memory:");
db << "CREATE TABLE tbl (id integer, name string);";
db << "INSERT INTO tbl VALUES (?, ?);" << 1 << "hello";
db << "INSERT INTO tbl VALUES (?, ?);" << 2 << "world";

vector<pair<int,string> > vec;
db << "select id,name from tbl;" >> tbl_functor(vec);

if(vec.size() != 2) {
cout << "Bad result on line " << __LINE__ << endl;
exit(EXIT_FAILURE);
}

vec.clear();

tbl_functor functor(vec);
db << "select id,name from tbl;" >> functor;

if(vec.size() != 2 || vec[0].first != 1 || vec[0].second != "hello") {
cout << "Bad result on line " << __LINE__ << endl;
exit(EXIT_FAILURE);
}

}
catch(sqlite_exception e) {
cout << "Unexpected error " << e.what() << endl;
exit(EXIT_FAILURE);
}
catch(...) {
cout << "Unknown error\n";
exit(EXIT_FAILURE);
}

cout << "OK\n";
exit(EXIT_SUCCESS);
}

0 comments on commit 709c4b5

Please sign in to comment.