質問するログイン新規登録

回答編集履歴

2

修正

2019/04/06 02:29

投稿

episteme
episteme

スコア16612

answer CHANGED
@@ -17,21 +17,28 @@
17
17
  #define GET_PROPERTY(X) X([this]() {return X##_; })
18
18
 
19
19
  // おためし
20
-
21
20
  #include <iostream>
22
21
  #include <string>
22
+ #include <chrono>
23
+ #include <ctime>
23
24
 
24
25
  class person {
25
26
  private:
26
27
  // プロパティ名に'_'を付けること。
27
28
  std::string name_;
28
29
  int age_;
30
+
29
31
  public:
30
32
  person(const std::string& n, int a) :
31
- name_(n), GET_PROPERTY(name),
33
+ name_(n), GET_PROPERTY(name),
32
- age_(a), GET_PROPERTY(age) {}
34
+ age_(a), GET_PROPERTY(age),
35
+ // 引数を取らない関数ならなんでも♪
36
+ now([]() -> std::string {
37
+ std::time_t t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
38
+ return std::ctime(&t); }) {}
33
39
  property<std::string> name;
34
40
  property<int> age;
41
+ property<std::string> now;
35
42
  };
36
43
 
37
44
  int main() {
@@ -39,6 +46,7 @@
39
46
  person adam("adam", 20);
40
47
  int age = adam.age; // do this
41
48
  cout << adam.name() << " is " // or this
42
- << age << " years old\n";
49
+ << age << " years old at "
50
+ << adam.now() << endl;
43
51
  }
44
52
  ```

1

追記

2019/04/06 02:28

投稿

episteme
episteme

スコア16612

answer CHANGED
@@ -1,1 +1,44 @@
1
- 五年も前に[こんなの](https://codezine.jp/article/detail/7571)書きました。
1
+ 五年も前に[こんなの](https://codezine.jp/article/detail/7571)書きました。
2
+ これをちょっといぢると:
3
+ ```C++
4
+ #include <functional>
5
+
6
+ template<class T>
7
+ class property {
8
+ private:
9
+ std::function<T()> get;
10
+ public:
11
+ property(const std::function<T()>& getter) : get(getter) {}
12
+ T operator()() const { return get(); }
13
+ operator T() const { return get(); }
14
+ typedef T value_type;
15
+ };
16
+
17
+ #define GET_PROPERTY(X) X([this]() {return X##_; })
18
+
19
+ // おためし
20
+
21
+ #include <iostream>
22
+ #include <string>
23
+
24
+ class person {
25
+ private:
26
+ // プロパティ名に'_'を付けること。
27
+ std::string name_;
28
+ int age_;
29
+ public:
30
+ person(const std::string& n, int a) :
31
+ name_(n), GET_PROPERTY(name),
32
+ age_(a), GET_PROPERTY(age) {}
33
+ property<std::string> name;
34
+ property<int> age;
35
+ };
36
+
37
+ int main() {
38
+ using namespace std;
39
+ person adam("adam", 20);
40
+ int age = adam.age; // do this
41
+ cout << adam.name() << " is " // or this
42
+ << age << " years old\n";
43
+ }
44
+ ```