1 | /* Copyright (C) 2013 Olivier Goffart <ogoffart@woboq.com> |
2 | http://woboq.com/blog/property-bindings-in-cpp.html |
3 | |
4 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and |
5 | associated documentation files (the "Software"), to deal in the Software without restriction, |
6 | including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, |
7 | and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, |
8 | subject to the following conditions: |
9 | |
10 | The above copyright notice and this permission notice shall be included in all copies or substantial |
11 | portions of the Software. |
12 | |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT |
14 | NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
15 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES |
16 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN |
17 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
18 | */ |
19 | |
20 | #include <iostream> |
21 | #include "property.h" |
22 | |
23 | int calculateArea(int width, int height) { |
24 | return (width * height) * 0.5; |
25 | } |
26 | |
27 | struct rectangle { |
28 | property<rectangle*> parent = nullptr; |
29 | property<int> width = 150; |
30 | property<int> height = 75; |
31 | property<int> area = [&]{ return calculateArea(width, height); }; |
32 | |
33 | property<std::string> color = [&]{ |
34 | if (parent() && area > parent()->area) |
35 | return std::string("blue" ); |
36 | else |
37 | return std::string("red" ); |
38 | }; |
39 | }; |
40 | |
41 | int main() { |
42 | rectangle parent; |
43 | rectangle child; |
44 | child.parent = &parent; |
45 | parent.width = 2; |
46 | std::cout << child.color() << std::endl; |
47 | //outputs "red" |
48 | } |
49 | |
50 | |