Skip to content

Commit 340979d

Browse files
authored
Merge pull request #14 from 4ms/callable
Fix callable function class
2 parents 8a4f166 + 07436e2 commit 340979d

File tree

2 files changed

+53
-3
lines changed

2 files changed

+53
-3
lines changed

tests/callable_tests.cc

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#include "doctest.h"
2+
#include "util/callable.hh"
3+
4+
TEST_CASE("Callable Function") {
5+
auto capture{0};
6+
auto func = Function<int(int, int)>{[&capture](int a, int b) {
7+
capture += 10;
8+
return a + b + capture;
9+
}};
10+
11+
CHECK(func(10, 10) == 30);
12+
CHECK(capture == 10);
13+
CHECK(func(10, 10) == 40);
14+
CHECK(capture == 20);
15+
}
16+
17+
TEST_CASE("Callable Function mixed params") {
18+
auto capture{0};
19+
auto func = Function<int(int, float)>{[&capture](int a, float b) {
20+
capture += 10;
21+
return a + b + capture;
22+
}};
23+
24+
CHECK(func(10, 10.f) == 30);
25+
CHECK(capture == 10);
26+
CHECK(func(10, 10.f) == 40);
27+
CHECK(capture == 20);
28+
}
29+
30+
TEST_CASE("Callable Function lots of params") {
31+
struct A {
32+
int a;
33+
char b;
34+
float d;
35+
double e;
36+
};
37+
auto capture{0};
38+
auto func = Function<int(int, float, char, A, A)>{[&capture](int a, float b, char x, A aa, A bb) {
39+
capture += 10;
40+
if (x == 'a')
41+
return aa.a + bb.b + capture * 2.f;
42+
else
43+
return a + b + capture;
44+
}};
45+
46+
CHECK(func(10, 10.f, 'x', {}, {2, 'b', 1.2f, 1.4}) == 30);
47+
CHECK(capture == 10);
48+
CHECK(func(10, 10.f, 'a', {}, {2, 'a', 1.2f, 1.4}) == 137);
49+
CHECK(capture == 20);
50+
}

util/callable.hh

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,19 +104,19 @@ public:
104104

105105
Ret call(Args... args) {
106106
if (m_callback)
107-
return m_callback(&m_data[0], std::forward<Args...>(args)...);
107+
return m_callback(&m_data[0], std::forward<Args>(args)...);
108108
return Ret();
109109
}
110110

111111
Ret operator()(Args... args) {
112-
return call(std::forward<Args...>(args)...);
112+
return call(std::forward<Args>(args)...);
113113
}
114114

115115
private:
116116
template<typename Callable>
117117
static Ret invoke(void *object, Args... args) {
118118
Callable &callable = *reinterpret_cast<Callable *>(object);
119-
callable(std::forward<Args...>(args)...);
119+
return callable(std::forward<Args>(args)...);
120120
}
121121

122122
template<typename Callable>

0 commit comments

Comments
 (0)