名稱空間
變體
操作

C++ 關鍵字: reflexpr (反射技術規範)

來自 cppreference.com
< cpp‎ | 關鍵字
 
 
C++ 語言
 
 

[編輯] 用法

1) 獲取 型別或 列舉 型別的成員列表或列舉器列表。
2) 獲取型別和成員的名稱。
3) 檢測資料成員是否為 staticconstexpr
4) 檢測成員函式是否為 virtualpublicprotectedprivate
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