Skip to content

Latest commit

 

History

History
83 lines (64 loc) · 2.36 KB

File metadata and controls

83 lines (64 loc) · 2.36 KB

annotations_of

  • meta[meta header]
  • std::meta[meta namespace]
  • function[meta id-type]
  • cpp26[meta cpp]
namespace std::meta {
  consteval std::vector<info> annotations_of(info item);
}
  • info[link info.md]

概要

宣言に付加されたすべてのアノテーションのリフレクションを取得する。

戻り値

itemに付加されたすべてのアノテーションのリフレクションを格納したstd::vectorオブジェクトを返す。

#include <meta>
#include <print>

struct Label { const char* text; };

struct [[=Label{std::define_static_string("my struct")}, =42]] S {};

int main() {
  static constexpr auto annots = std::define_static_array(std::meta::annotations_of(^^S));
  // annotsはconsteval-only型のため、実行時に使うにはサイズなどを
  // 定数式としてあらかじめ取り出しておく必要がある
  constexpr std::size_t count = annots.size();
  std::println("アノテーション数: {}", count);

  template for (constexpr auto a : annots) {
    // アノテーションの型名を出力
    std::println("  型: {}", std::meta::display_string_of(std::meta::type_of(a)));

    // 型ごとに値を取り出して出力
    // アノテーションは値のリフレクションではないため、
    // constant_of()で値を取り出してからスプライスする
    if constexpr (std::meta::type_of(a) == ^^const Label) {
      std::println("  値: {}", [:std::meta::constant_of(a):].text);
    } else if constexpr (std::meta::type_of(a) == ^^int) {
      std::println("  値: {}", [:std::meta::constant_of(a):]);
    }
  }
}
  • std::meta::display_string_of[link display_string_of.md]
  • std::meta::type_of[link type_of.md]
  • std::meta::constant_of[link constant_of.md]

出力

アノテーション数: 2
  型: const Label
  値: my struct
  型: int
  値: 42

バージョン

言語

  • C++26

処理系

関連項目

参照