SHOW:
|
|
- or go back to the newest paste.
1 | - | C++11 Quiz ( Type Traits ) |
1 | + | |
2 | - | ======================= |
2 | + | |
3 | - | Let's say I have the following piece of code. |
3 | + | |
4 | { | |
5 | virtual void play_strategy() const | |
6 | { | |
7 | std::cout << "Watching television" << std::endl; | |
8 | } | |
9 | virtual ~Mom() { } | |
10 | }; | |
11 | ||
12 | struct FemaleChild: Mom | |
13 | { | |
14 | virtual void play_strategy() const override | |
15 | { | |
16 | std::cout << "Playing with dolls" << std::endl; | |
17 | } | |
18 | }; | |
19 | ||
20 | struct MaleChild: Mom | |
21 | { | |
22 | virtual void play_strategy() const override | |
23 | { | |
24 | std::cout << "Kicking football around" << std::endl; | |
25 | } | |
26 | }; | |
27 | struct UnrelatedWitchMom | |
28 | { | |
29 | void play_strategy() const | |
30 | { | |
31 | std::cout << "Killing innocent children" << std::endl; | |
32 | } | |
33 | }; | |
34 | ||
35 | template <typename T, | |
36 | typename = typename std::enable_if<std::is_base_of<Mom, T>::value>::type> | |
37 | void play_type(T *obj) | |
38 | { | |
39 | obj->play_strategy(); | |
40 | } | |
41 | ||
42 | int main() | |
43 | { | |
44 | Mom my_mom {}; | |
45 | Mom *you = new FemaleChild{}, *me = new MaleChild{}; | |
46 | ||
47 | play_type( &my_mom ); | |
48 | play_type( you ); | |
49 | play_type( me ); | |
50 | ||
51 | UnrelatedWitchMom mom_ah {}; | |
52 | play_type( &mom_ah ); | |
53 | ||
54 | delete you; | |
55 | delete me; | |
56 | ||
57 | - | In C++, I know that I can make a template function that accepts any class object, like: |
57 | + | |
58 | - | template <class T> void iAcceptAnything(T x) |
58 | + | } |