File tree Expand file tree Collapse file tree
reference/meta/access_context Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -21,32 +21,47 @@ consteval access_context via(info cls) const;
2121
2222
2323## 例
24+ `via()`は、protectedメンバへのアクセス可否を決める「派生クラス経由」の文脈を切り替える。protectedメンバの可視性は、スコープ(呼び出し元)が指定クラスのメンバまたは派生クラスのメンバである場合にのみ許可される。
25+
2426```cpp example
2527#include <meta>
2628#include <print>
2729
2830class Base {
29- protected:
30- int prot = 1;
3131public:
32- int pub = 2;
32+ int pub = 1;
33+ protected:
34+ int prot = 2;
3335};
3436
35- class Derived : public Base {};
37+ class Derived : public Base {
38+ public:
39+ static void check_inside() {
40+ // スコープはDerivedのメンバ関数 = Derivedの内部からのアクセス
41+ // via(Derived)によりDerived経由のアクセスとして扱われ、Baseのprotにもアクセス可能
42+ constexpr auto ctx = std::meta::access_context::current().via(^^Derived);
43+ constexpr auto count = std::meta::nonstatic_data_members_of(^^Base, ctx).size();
44+ std::println("Derived内からvia(Derived): {}", count); // pub と prot の2個
45+ }
46+ };
3647
3748int main() {
38- // Derived経由でBaseのメンバにアクセス
49+ // スコープはmain() = Derivedの外部からのアクセス
50+ // via(Derived)してもmain()はDerivedの一員ではないため、protはアクセス不可
3951 constexpr auto ctx = std::meta::access_context::current().via(^^Derived);
4052 constexpr auto count = std::meta::nonstatic_data_members_of(^^Base, ctx).size();
41- std::println("Derived経由で見えるメンバ数: {}", count);
53+ std::println("main()からvia(Derived): {}", count); // pubのみの1個
54+
55+ Derived::check_inside();
4256}
4357```
4458* via[ color ff0000]
4559* std::meta::nonstatic_data_members_of[ link ../nonstatic_data_members_of.md]
4660
4761### 出力
4862```
49- Derived経由で見えるメンバ数: 2
63+ main()からvia(Derived): 1
64+ Derived内からvia(Derived): 2
5065```
5166
5267## バージョン
You can’t perform that action at this time.
0 commit comments