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

回答編集履歴

2

見せ消しの訂正です。

2020/06/28 15:37

投稿

anndonut
anndonut

スコア667

answer CHANGED
@@ -1,6 +1,6 @@
1
- ~~シングルトンパターンを適用すると初期化を1回に抑えることができます。
1
+ ~~シングルトンパターンを適用すると初期化を1回に抑えることができます。~~
2
2
 
3
- [シングルトンのベターな実装方法](https://qiita.com/kikuuuty/items/fcf5f7df2f0493c437dc)~~
3
+ ~~[シングルトンのベターな実装方法](https://qiita.com/kikuuuty/items/fcf5f7df2f0493c437dc)~~
4
4
 
5
5
  [追記] 自分なりに不細工なコードを書いてみました。
6
6
 

1

グローバル関数、変数によるコードを追記

2020/06/28 15:37

投稿

anndonut
anndonut

スコア667

answer CHANGED
@@ -1,3 +1,64 @@
1
- シングルトンパターンを適用すると初期化を1回に抑えることができます。
1
+ ~~シングルトンパターンを適用すると初期化を1回に抑えることができます。
2
2
 
3
- [シングルトンのベターな実装方法](https://qiita.com/kikuuuty/items/fcf5f7df2f0493c437dc)
3
+ [シングルトンのベターな実装方法](https://qiita.com/kikuuuty/items/fcf5f7df2f0493c437dc)~~
4
+
5
+ [追記] 自分なりに不細工なコードを書いてみました。
6
+
7
+ ```C++
8
+ #include <iostream>
9
+ #include <vector>
10
+ #include <map>
11
+ #include <string>
12
+
13
+ static std::vector<std::string> getPaths(size_t typeHash, const std::string typeName, const std::string path) {
14
+ static std::map<std::size_t, std::vector<std::string>> m;
15
+ if (m.count(typeHash) == 0) {
16
+ std::cout << "DEBUG: 呼び出されたよん" << std::endl;
17
+ std::vector<std::string> v;
18
+ v.push_back(std::string() + typeName + "の" + path + "でなんか適当なやつ1");
19
+ v.push_back(std::string() + typeName + "の" + path + "でなんか適当なやつ2");
20
+ v.push_back(std::string() + typeName + "の" + path + "でなんか適当なやつ3");
21
+ m.insert(std::make_pair(typeHash, v));
22
+ }
23
+ return m[typeHash];
24
+ }
25
+
26
+ class Base {
27
+ protected:
28
+ std::vector<std::string> paths;
29
+
30
+ public:
31
+ Base(size_t typeHash, std::string typeName, std::string path) {
32
+ paths = getPaths(typeHash, typeName, path);
33
+ };
34
+
35
+ void printPaths() {
36
+ for (auto p: paths)
37
+ std::cout << p << std::endl;
38
+ };
39
+ };
40
+
41
+ class A : public Base {
42
+ public: A() : Base(typeid(this).hash_code(), typeid(this).name(), std::string("Path1")) { };
43
+ };
44
+ class B : public Base {
45
+ public: B() : Base(typeid(this).hash_code(), typeid(this).name(), std::string("Path2")) { };
46
+ };
47
+
48
+
49
+ int main() {
50
+ {
51
+ A a;
52
+ a.printPaths();
53
+ }
54
+ {
55
+ B b;
56
+ b.printPaths();
57
+ }
58
+ {
59
+ A a;
60
+ a.printPaths();
61
+ }
62
+ return 0;
63
+ }
64
+ ```