在C++11中无实例获取unique_ptr内std::array的大小
要在C++11中从std::unique_ptr<std::array<uint8_t, N>>类型中获取内部array的大小,无需创建实例,可以借助std::remove_pointer和std::tuple_size组合实现,具体步骤和代码如下:
实现思路
- 提取指向类型:通过
<type_traits>头文件中的std::remove_pointer,从unique_ptr类型中剥离出它指向的std::array原始类型。 - 获取编译期大小:将提取到的
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,提问作者אנונימי
相关产品推荐
相关产品推荐

