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

标签 c++ templates

这是一个展示我本质上想做的事情的例子

// 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;
    }
}

在此示例中,这将打印出错误消息。有什么办法吗?我遇到这个问题的原因是我收到了一些正在传递给 processbase_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 单例来解决潜在的冲突。

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

关于c++ - 获取模板参数的成员变量值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50298270/

相关文章:

c++ - QODBC3 无法绑定(bind)到变量

c++ - Cout 和 Cerr 不同步

程序中的 C++ 错误

c++ - 实例化后模板的特化?

用于非类型模板参数的 c++ enable_if

ruby - 如何使用 Thor 模板在作用域内创建 ruby​​ 变量和方法?

c++ - 编译器生成构造函数来初始化成员

c++ - 模板函数查找

c++ - 部分模板特化类型折叠规则

c++ - 函数模板的模糊重载