获取模板参数的成员变量值列表

Get a list of values of member variable for template parameters

本文关键字:成员 变量值 列表 参数 获取      更新时间:2023-10-16

这里有一个例子,展示了我本质上想要做的事情

// 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,所以我希望这可以拯救我。

以下是我的做法:

而不是对类型 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*>中。因为这一切都发生在初始化期间,我们需要确保 init 顺序不会给我们带来问题,因此我们使用 Meyer 单例来解决潜在的冲突。

从那里,您所要做的就是在程序执行期间从向量中检索 ID。