c++ - 获取模板参数的成员变量值列表
问题描述
这是一个示例,显示了我本质上想要做的事情
// 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*>
. 因为这都是在初始化期间发生的,所以我们需要确保初始化顺序不会给我们带来问题,因此我们使用 Meyer 单例来解决潜在的冲突。
从那里,您所要做的就是在程序执行期间从向量中检索 id。
推荐阅读
- android - 用户消息平台:重置同意
- macos - Docker(compose v3)静态IP,不绑定到本地主机 - Mac
- python - 为什么 file.read() 在 python 中返回 ''
- python - 无法在 python 中加载 facenet_keras.h5 模型
- php - 我无法按我的意愿显示程序
- python - 从python中的日期转换的一天、一周和一个月的分数
- javascript - 如何制作 3D 光滑滑块
- apache - 如何使用 Telnet 发送 HTTP 请求?
- reactjs - 我收到此错误,我不知道该怎么办,“TypeError:render is not a function”
- angular - 如何使用 Angular 11 在 ngFor 中设置临时变量?