获取模板参数的成员变量值列表
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
转换为派生类型。实际上一切都已经有了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。
相关文章:
- 使用变量值作为 PlaySound 中的路径
- 通过指针偏移量访问结构变量值
- 变量值在 C++ 中的 glutIdleFunc() 中未递增
- 更新 #ifdef 中的现有变量值?
- 尝试更改 main 函数内的全局变量值时出现编译错误 C++.
- 通过 Rcpp 和 bit64 R 包将最大的int64_t变量值从 C++ 传递到 R
- 如何使用 IRBuilder 更新 LLVM IR 中的全局变量值?
- 更改已在运行的程序的变量值
- 在 Xcode 中使用后对外部变量值进行初始化
- C++整数变量值
- 获取模板参数的成员变量值列表
- 使用特定成员变量值创建类型的类型
- 对象在将操作推送到向量后成员变量值已更改
- 根据C 中的变量值创建成员函数
- 初始化静态成员变量值的正确位置
- 观察成员变量值的变化
- C++ 成员变量值根据是否打印出来而变化
- 轨道成员变量值更改
- 为什么我的析构函数没有破坏我的对象,它仍然保留其成员变量值
- C++当我离开默认构造函数时,我的初始化字符串消失了,但我的其他成员变量值没有