Skip to content

Commit 709c4b5

Browse files
committed
Merge pull request #42 from aminroosta/functors
Fixes #11
2 parents 93ccd4e + e03e427 commit 709c4b5

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

Diff for: hdr/sqlite_modern_cpp/utility/function_traits.h

+21
Original file line numberDiff line numberDiff line change
@@ -31,5 +31,26 @@ namespace sqlite {
3131
static const std::size_t arity = sizeof...(Arguments);
3232
};
3333

34+
/* support the non-const operator ()
35+
* this will work with user defined functors */
36+
template <
37+
typename ClassType,
38+
typename ReturnType,
39+
typename... Arguments
40+
>
41+
struct function_traits<
42+
ReturnType(ClassType::*)(Arguments...)
43+
> {
44+
typedef ReturnType result_type;
45+
46+
template <std::size_t Index>
47+
using argument = typename std::tuple_element<
48+
Index,
49+
std::tuple<Arguments...>
50+
>::type;
51+
52+
static const std::size_t arity = sizeof...(Arguments);
53+
};
54+
3455
}
3556
}

Diff for: tests/functors.cc

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
#include <string>
5+
#include <sqlite_modern_cpp.h>
6+
7+
using namespace sqlite;
8+
using namespace std;
9+
10+
struct tbl_functor {
11+
explicit tbl_functor(vector<pair<int, string> > &vec_) : vec(vec_) { }
12+
13+
void operator() ( int id, string name) {
14+
vec.push_back(make_pair(id, move(name)));
15+
}
16+
vector<pair<int,string> > &vec;
17+
};
18+
19+
int main() {
20+
21+
try {
22+
database db(":memory:");
23+
db << "CREATE TABLE tbl (id integer, name string);";
24+
db << "INSERT INTO tbl VALUES (?, ?);" << 1 << "hello";
25+
db << "INSERT INTO tbl VALUES (?, ?);" << 2 << "world";
26+
27+
vector<pair<int,string> > vec;
28+
db << "select id,name from tbl;" >> tbl_functor(vec);
29+
30+
if(vec.size() != 2) {
31+
cout << "Bad result on line " << __LINE__ << endl;
32+
exit(EXIT_FAILURE);
33+
}
34+
35+
vec.clear();
36+
37+
tbl_functor functor(vec);
38+
db << "select id,name from tbl;" >> functor;
39+
40+
if(vec.size() != 2 || vec[0].first != 1 || vec[0].second != "hello") {
41+
cout << "Bad result on line " << __LINE__ << endl;
42+
exit(EXIT_FAILURE);
43+
}
44+
45+
}
46+
catch(sqlite_exception e) {
47+
cout << "Unexpected error " << e.what() << endl;
48+
exit(EXIT_FAILURE);
49+
}
50+
catch(...) {
51+
cout << "Unknown error\n";
52+
exit(EXIT_FAILURE);
53+
}
54+
55+
cout << "OK\n";
56+
exit(EXIT_SUCCESS);
57+
}

0 commit comments

Comments
 (0)