创建类型列表并访问每种类型的静态成员?

Create a list of types and access a static member of each type?

本文关键字:类型 静态成员 种类 访问 列表 创建      更新时间:2023-10-16

我有许多子类,它们都有一个静态type_id字段。我正在尝试做的是保存一个类型列表(通过搜索,我知道这是一个敏感的主题(,然后访问我的类型列表中的类型type_id。下面是一个示例

// Example program
#include <iostream>
#include <tuple>
struct base_type
{
static const uint64_t type_id = 0;
};
struct A : public base_type
{
static const uint64_t type_id = 1;
};
struct B : public base_type
{
static const uint64_t type_id = 2;
};
struct C : public base_type
{
static const uint64_t type_id = 3;
};

template <class... Args>
struct type_list
{
template <std::size_t N>
using type = typename std::tuple_element<N, std::tuple<Args...>>::type;
};
int main()
{
using my_types = type_list<base_type, A, B, C>;
std::cout << my_types::type<1>.type_id << std::endl;
}

然后希望这会打印出 1。但是,如果您尝试编译它,它将不起作用。有没有办法实现这样的事情?


编辑:解决方案非常简单,我很惭愧。只需要my_types::type<1>::type_id而不是my_types::type<1>.type_id

从类型访问静态成员使用::.

my_types::type<1>::type_id