簡體   English   中英

獲取模板參數的成員變量值列表

[英]Get a list of values of member variable for template parameters

這是一個示例,顯示了我實際上要嘗試執行的操作

// Example program
#include <iostream>
#include <vector>

struct base_type
{
    static const uint64_t type_id = 0x0;
};

struct A : public base_type
{
    static const uint64_t type_id = 0xA;
};

struct B : public base_type
{
    static const uint64_t type_id = 0xB;
};

struct C : public base_type
{
    static const uint64_t type_id = 0xC;
};


template <class... Args>
struct processor
{
    void process(Args... args);

    // NEED HELP WITH HOW THIS WOULD WORK
    // Essentially I want a fucntion that can extract
    // the type_id of each of the template parameters
    std::vector<uint64_t> get_type_ids()
    {
        // What should go in here?
    }
};

int main()
{
    processor<A, B> my_processor;
    B b;
    C c;
    // Here's the part that I am stuck on
    // THIS IS PSEUDOCODE
    if (b.type_id in my_processor.get_type_ids() and c.type_id in my_processor.get_type_ids())
    {
        my_processor.process(b, c);
    }
    else
    {
        std::cout << "One of the arguments to process was not the correct type" << std::endl;
    }
}

在此示例中,這將打印出錯誤消息。 有什么辦法嗎? base_type此問題的原因是,我收到了許多要傳遞給processbase_type對象,但我需要事先檢查base_type是否可以安全地轉換為派生類型。 實際上,所有內容都已經具有type_id因此我希望可以救我。

這是我的處理方式:

而不是使用標量類型作為類型ID,例如:

static const uint64_t type_id = 0x0;

我會用構造函數創建一個專用類型:

static const my_meta_type type_id;

my_meta_type A::type_id{0x00};

my_meta_type看起來像這樣:

class my_meta_type {
  static std::vector<my_meta_type const*>& registered_types(); //Meyer's singleton
  uint64_t id_;
public:
  my_meta_type(uint64_t id) 
    : id_(id) {
    registered_types().emplace_back(this);
  }
};

std::vector<my_meta_type*>& my_meta_type::registered_types() {
  static std::vector<my_meta_type const*> instance;
  return instance;
}

這將是在初始化期間運行my_meta_type的構造函數,並將指針實例放在vector<my_meta_type*> 因為這都是在初始化期間發生的,所以我們需要確保初始化順序不會引起問題,因此我們使用Meyer單例來解決潛在的沖突。

從那里開始,您要做的就是在程序執行期間從向量中檢索ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM