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

如何编写constexpr函数计算std::vector的嵌套深度

完全可以通过模板元编程配合constexpr求值规则实现该需求,所有计算逻辑在编译期完成,无任何运行时开销,完全匹配你给出的调用形式。

实现代码(兼容C++11及以上标准)
#include <vector>
#include <type_traits>

// 基础模板:非std::vector类型的嵌套深度为0
template <typename T>
struct vector_depth : std::integral_constant<int, 0> {};

// 特化模板:匹配std::vector<T>类型,深度为1加内部类型T的嵌套深度
template <typename T>
struct vector_depth<std::vector<T>> : std::integral_constant<int, 1 + vector_depth<T>::value> {};

// 封装为要求的constexpr模板函数
template <typename T>
constexpr int get_vector_nested_layer_count() {
    return vector_depth<T>::value;
}
效果验证

以下测试代码可以直接通过编译期校验,和你给出的示例预期完全一致:

int main() {
    // 对应示例1,返回值为2
    constexpr int d1 = get_vector_nested_layer_count<std::vector<std::vector<int>>>();
    static_assert(d1 == 2, "depth mismatch");

    // 对应示例2,返回值为3
    constexpr int d2 = get_vector_nested_layer_count<std::vector<std::vector<std::vector<float>>>>();
    static_assert(d2 == 3, "depth mismatch");

    // 边界场景校验:非vector类型返回0,单层vector返回1
    constexpr int d3 = get_vector_nested_layer_count<int>(); // 0
    constexpr int d4 = get_vector_nested_layer_count<std::vector<char>>(); // 1
    static_assert(d3 == 0 && d4 == 1, "edge case mismatch");
    
    return 0;
}
实现说明
  • 核心逻辑依赖C++模板的递归匹配规则:遇到std::vector<T>类型时自动递归拆解内部类型计数,遇到非vector类型时触发基础模板终止递归。
  • 函数返回值是纯正的编译期常量,可以直接用于数组长度声明、模板参数、编译期断言等所有要求constexpr值的场景。
  • 如果使用C++17及更新的标准,可以用变量模板进一步简化实现,无需封装单独的调用函数:
// C++17 简化版实现
template <typename T>
constexpr int vector_depth_v = 0;

template <typename T>
constexpr int vector_depth_v<std::vector<T>> = 1 + vector_depth_v<T>;

// 直接调用即可:vector_depth_v<std::vector<std::vector<int>>> 结果为2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 15:51:41