创建类型列表并访问每种类型的静态成员?
Create a list of types and access a static member of each type?
我有许多子类,它们都有一个静态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
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 从相同类型的静态成员进行类内初始化
- 在类定义中推导内联静态成员函数的返回类型
- 如何声明和定义具有推导类型的静态成员
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- 初始化在类类型 #define 中定义的非静态成员数组,不带默认 ctor
- 初始化与类类型相同的静态成员(静态初始化顺序问题)
- 缺少类型说明符 - int 假定 声明静态成员后出错
- 定义非静态成员时获取C++中的"this"类型
- 创建类型列表并访问每种类型的静态成员?
- 如果静态成员未初始化并且成员类型是类本身,该怎么办?
- 类型为专用数据成员的静态成员
- 参考类型静态数据成员的问题可能是编译器错误
- 提升侵入性unordered_set静态成员功能返回错误的尺寸类型
- 如果我创建一个修改值的迭代器,静态成员"reference"应该是什么类型?
- 静态成员函数中封闭类的C++类型
- 为什么constexpr静态成员(类型为class)需要定义
- 当类类型未知时,指向非静态成员函数的函数指针
- 基于静态成员类型的模板函数专用化