[英]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
此问题的原因是,我收到了许多要传递给process
的base_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.