首页 > 解决方案 > 获取模板参数的成员变量值列表

问题描述

这是一个示例,显示了我本质上想要做的事情

// 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正在传递的对象,process但我需要事先检查是否base_type可以安全地转换为派生类型。事实上,一切都type_id已经有了,所以我希望它能救我。

标签: c++templates

解决方案


这是我将如何做到这一点:

而不是对类型 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。


推荐阅读