Template-template parameters

虽说早就听闻C++的模版是图灵完全的,不过当看到这样的用法的时候,还是不禁感叹这实在是太酷了!写Haskell风格的C++指日可待!

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
template <template <typename> class m>
struct Monad {
template <typename a>
static m<a> mreturn(const a&);

template <typename a, typename b>
static m<b> mbind(const m<a>&, m<b>(*)(const a&));
};

template <typename a>
struct Maybe {
bool isNothing;
a value;
};

template <>
struct Monad<Maybe> {
template <typename a>
static Maybe<a> mreturn(const a& v) {
Maybe<a> x;
x.isNothing = false;
x.value = v;
return x;
}

template <typename a, typename b>
static Maybe<b> mbind(const Maybe<a>& action, Maybe<b>(*function)(const a&)) {
if (action.isNothing)
return action;
else
return function(action.value);
}
};

相关链接:

Higher-kinded Types with C++

What are some uses of template template parameters in C++?