You need to enable JavaScript to run this app. C++17下如何实现保留cv与引用限定符的类型容器
优惠活动
大模型
产品
解决方案
定价
更多

C++17下如何实现保留cv与引用限定符的类型容器

C++17 类型容器实现方案

完整实现代码

#include <cstddef>
#include <utility>

// 核心类型容器,存储任意数量的类型
template <typename... Ts>
struct classContainer {};

// 按索引提取类型的内部萃取实现
template <size_t Idx, typename... Ts>
struct type_at_index_impl;

template <size_t Idx, typename T, typename... Ts>
struct type_at_index_impl<Idx, T, Ts...> : type_at_index_impl<Idx - 1, Ts...> {};

template <typename T, typename... Ts>
struct type_at_index_impl<0, T, Ts...> {
    using type = T;
};

template <typename Container, size_t Idx>
struct type_at_index;

template <size_t Idx, typename... Ts>
struct type_at_index<classContainer<Ts...>, Idx> {
    using type = typename type_at_index_impl<Idx, Ts...>::type;
};

// 对外的类型提取别名,可直接用于变量声明
template <typename Container, size_t Idx>
using getType = typename type_at_index<Container, Idx>::type;

// 从传入参数推导生成类型容器,完整保留所有cv、引用限定符
template <typename... Args>
constexpr auto makeClassContainer(Args&&... args) noexcept {
    return classContainer<decltype(std::forward<Args>(args))...>{};
}

实现说明

  • classContainer 是纯类型容器,本身不存储任何实例,仅通过可变模板参数承载类型列表,可在任意上下文传递作为类型参数,符合C++17语法规范,无第三方依赖。
  • makeClassContainer 使用万能引用接收参数,通过 std::forward 结合 decltype 完整保留参数的const/volatile限定符、左值/右值引用属性,不会发生类似std::make_tuple的类型退化问题。

    如果你不需要保留引用限定,仅需要保留cv限定,可将返回类型修改为 classContainer<std::remove_reference_t<decltype(std::forward<Args>(args))>...>,即可匹配你示例注释中的类型推导结果。

  • getType 是别名模板,支持按索引从classContainer中提取对应位置的类型,可直接用于变量声明,索引越界时会直接触发编译错误,符合常规容器的访问行为。

使用测试

#include <string>
#include <any> // 可用boost::any完全替代,效果一致

int main() {
    int integer = 0xDEADBEEF;
    std::string hello ("hello");
    std::any c (integer);
    const int c_deadbeef = integer;
    int& cr_deadbeef (integer);

    // 推导类型容器
    using oneClassContainer = decltype( makeClassContainer(integer, hello, c, c_deadbeef, cr_deadbeef) );
    // 默认实现得到的类型是 classContainer<int&, std::string&, std::any&, const int&, int&>
    // 若修改为去掉引用的版本,得到的类型是 classContainer<int, std::string, std::any, const int, int&>,和示例注释完全一致

    using anotherClassContainer = classContainer<int, const int&, const int>;

    // 按索引取类型声明变量
    getType<anotherClassContainer,0> anotherInt = 3; // 类型为int
    getType<anotherClassContainer,1> constIntRef (anotherInt); // 类型为const int&
    getType<anotherClassContainer,2> constInt = 3; // 类型为const int

    return 0;
}

内容的提问来源于stack exchange,提问作者Jayeon Yi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 19:30:05