You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建类型列表并访问各类型的static type_id成员?

问题:无法访问类型列表中类型的static成员type_id

你尝试创建一个包含多个继承自base_type的类型列表,并访问其中类型的static uint64_t 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;
}

错误原因

你这里的问题出在访问静态成员的语法上:my_types::type<1>是一个类型(也就是A),而不是某个对象的实例。在C++中,访问类型的静态成员需要使用作用域解析符::,而不是用于实例成员的.运算符。

修正后的代码

只需要把访问type_id的语句改成my_types::type<1>::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。

内容的提问来源于stack exchange,提问作者Nick Chapman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:17:34