C++ 關鍵字: reflexpr
(反射技術規範)
來自 cppreference.com
[編輯] 用法
2) 獲取型別和成員的名稱。
5) 獲取型別定義時原始碼的行和列。
[編輯] 示例
reflexpr
透過元物件型別為我們提供物件的元資訊。請注意,std::reflect::get_data_members_t
使程式設計師能夠像 std::tuple 一樣訪問任何類。
執行此程式碼
#include <string> #include <vector> struct S { int b; std::string s; std::vector<std::string> v; }; // Reflection TS #include <experimental/reflect> using meta_S = reflexpr(S); using mem = std::reflect::get_data_members_t<meta_S>; using meta = std::reflect::get_data_members_t<mem>; static_assert(std::reflect::is_public_v<meta>); // successful int main() {}
我們也可以從 reflexpr
中獲取名稱資訊
執行此程式碼
#include <iostream> #include <string> #include <string_view> // Reflection TS #include <experimental/reflect> template<typename Tp> constexpr std::string_view nameof() { using TpInfo = reflexpr(Tp); using aliased_Info = std::experimental::reflect::get_aliased_t<TpInfo>; return std::experimental::reflect::get_name_v<aliased_Info>; } int main() { std::cout << nameof<std::string>() << '\n'; static_assert(nameof<std::string>() == "basic_string"); // successful }
這是一個在 反射技術規範 中獲取型別作用域的示例。
執行此程式碼
namespace Foo { struct FooFoo { int FooFooFoo; }; } namespace Bar { using BarBar = ::Foo::FooFoo; } using BarBarInfo = reflexpr(::Bar::BarBar); using BarBarScope = ::std::experimental::reflect::get_scope_t<BarBarInfo>; // Bar, not Foo struct Spam { int SpamSpam; }; struct Grok { using GrokGrok = Spam::SpamSpam; }; using GrokGrokInfo = reflexpr(::Grok::GrokGrok); using GrokGrokScope = std::experimental::reflect::get_scope_t<GrokGrokInfo>; // Grok, not Spam