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

在C++11中无实例获取unique_ptr内std::array的大小

要在C++11中从std::unique_ptr<std::array<uint8_t, N>>类型中获取内部array的大小,无需创建实例,可以借助std::remove_pointer和std::tuple_size组合实现,具体步骤和代码如下:

实现思路

  1. 提取指向类型:通过<type_traits>头文件中的std::remove_pointer,从unique_ptr类型中剥离出它指向的std::array原始类型。
  2. 获取编译期大小:将提取到的array类型传入std::tuple_size,直接获取编译期确定的array大小值。

完整代码示例

#include <memory>
#include <array>
#include <type_traits>

// 你的类型定义
constexpr size_t N = 16;
using Buffer = std::unique_ptr<std::array<uint8_t, N>>;

// 模板函数实现
template<typename Buffer>
bool temp_func()
{
    // 从unique_ptr中提取指向的std::array类型
    using ArrayType = typename std::remove_pointer<Buffer>::type;
    // 获取array的编译期大小
    constexpr size_t array_size = std::tuple_size<ArrayType>::value;

    // 示例操作:用静态断言验证大小(可选)
    static_assert(array_size == N, "Array size does not match expected value");

    // 后续业务逻辑...
    return true;
}

// 调用示例
int main()
{
    temp_func<Buffer>();
    return 0;
}

这种方式完全在编译期完成类型推导和大小计算,不需要创建任何实例,完全符合C++11标准的要求。

内容的提问来源于stack exchange,提问作者אנונימי

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:37:15