如何将std::array或std::vector作为模板类型传递给模板参数
实现支持std::array和std::vector的convert函数模板(C++11/14)
核心思路
由于函数模板无法偏特化,我们借助类模板偏特化分别实现std::array和std::vector的转换逻辑,再通过统一的函数模板对外暴露调用接口。既满足返回类型由模板参数指定的要求,又能让编译器自动推导输入参数的类型。
完整实现代码
#include <array> #include <vector> #include <cstdint> #include <cstring> #include <type_traits> // 辅助类模板:定义不同容器的转换规则 template<template<typename, typename...> class TargetContainer, typename SourceType> struct Converter; // 针对std::array的特化:数组大小由SourceType的sizeof决定,元素固定为uint8_t template<typename SourceType> struct Converter<std::array, SourceType> { using ResultType = std::array<uint8_t, sizeof(SourceType)>; static ResultType convert(SourceType value) { ResultType result; std::memcpy(result.data(), &value, sizeof(SourceType)); return result; } }; // 针对std::vector的特化:元素固定为uint8_t,长度等于SourceType的sizeof template<typename SourceType> struct Converter<std::vector, SourceType> { using ResultType = std::vector<uint8_t>; static ResultType convert(SourceType value) { ResultType result(sizeof(SourceType)); std::memcpy(result.data(), &value, sizeof(SourceType)); return result; } }; // 对外统一调用的函数模板 template<template<typename, typename...> class TargetContainer, typename SourceType> typename Converter<TargetContainer, SourceType>::ResultType convert(SourceType value) { return Converter<TargetContainer, SourceType>::convert(value); }
测试验证
int main() { // 测试std::array转换 auto x = convert<std::array>(6000); // x类型为std::array<uint8_t, 4> auto y = convert<std::array>(1.02322); // y类型为std::array<uint8_t, 8> // 测试std::vector转换 auto z = convert<std::vector>(6000); // z类型为std::vector<uint8_t>,长度4 // 静态断言验证类型正确性 static_assert(std::is_same<decltype(x), std::array<uint8_t, 4>>::value, "x类型错误"); static_assert(std::is_same<decltype(y), std::array<uint8_t, 8>>::value, "y类型错误"); static_assert(std::is_same<decltype(z), std::vector<uint8_t>>::value, "z类型错误"); return 0; }
说明
- 模板模板参数:
TargetContainer用来接收std::array或std::vector这类模板容器类型,编译器会自动匹配对应的特化类。 - 内存拷贝:使用
std::memcpy完成原始数据到字节数组/向量的转换,保证效率且兼容C++11标准。 - 类型安全:通过
static_assert可以在编译期验证转换后的类型是否符合预期。
内容的提问来源于stack exchange,提问作者Nelsen Edbert Winata
相关产品推荐
相关产品推荐

