-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdefault.cpp
61 lines (48 loc) · 1.27 KB
/
default.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include "../tc_alt.hpp"
// This file illustrates one of the most useful typeclass features:
// support of default methods.
//
// In contrast with a C-with-classes style of abstract-class interfaces
// our typeclass implementation implicitly uses a sort of CRTP so
// the methods are resolved statically with no overhead of virtual calls.
TC_DEF(Foo, class T, {
static int foo(int x) {
return Foo<T>::bar(x) + 1;
}
static int bar(int x) {
return Foo<T>::foo(x) - 1;
}
});
struct Bar; struct Baz; struct Quuz;
template<>
TC_INSTANCE(Foo, Bar, {
static int foo(int x) {
return x;
}
})
template<>
TC_INSTANCE(Foo, Baz, {
static int bar(int x) {
return x-1;
}
})
// for optimization purposes one may define something larger than
// a minimal set of required methods
template<>
TC_INSTANCE(Foo, Quuz, {
static int foo(int x) {
return x;
}
static int bar(int x) {
return x-1;
}
})
int main() {
std::cout << Foo<Bar>::foo(1) << " "
<< Foo<Bar>::bar(1) << std::endl;
std::cout << Foo<Baz>::foo(1) << " "
<< Foo<Baz>::bar(1) << std::endl;
std::cout << Foo<Quuz>::foo(1) << " "
<< Foo<Quuz>::bar(1) << std::endl;
}