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

如何用折叠表达式展开NTTP参数包?解决MSVC C7515错误

解决MSVC下折叠表达式展开NTTP参数包的编译错误

你编写了接收非类型模板参数(NTTP)包的函数bar,试图通过折叠表达式将参数包内每个元素作为foo的模板参数展开,但在MSVC中遇到编译错误。相关代码如下:

#include <iostream>
#include <string_view>
#include <type_traits>

struct TestStruct
{};

template <typename Type>
struct TypedTestDesc {
  using TestTypeT = Type;
  const char* m_typeName;
};

template <auto TypedTestDesc>
void foo()
{
  if constexpr (std::is_default_constructible_v<typename TypedTestDesc::TestTypeT>) {
    std::cout << TypedTestDesc.m_typeName << "\n";
    typename TypedTestDesc::TestTypeT tmp {};
  }
}

template <auto ...TypedTestDescList>
void bar()
{
  (foo<TypedTestDesc>(), ...); // 错误行
}

int main()
{
  foo<TypedTestDesc<TestStruct>{"TestStruct"}>();
}

编译错误信息

MSVC编译错误:(27): error C7515: 折叠表达式必须包含未展开的参数包

问题原因与修复

错误根源是折叠表达式中引用的TypedTestDesc并非参数包的元素名,参数包实际定义为TypedTestDescList,导致编译器无法识别需要展开的参数包。只需修正折叠表达式中的变量名即可:

修正后的bar函数:

template <auto ...TypedTestDescList>
void bar()
{
  (foo<TypedTestDescList>(), ...);
}

另外注意原foo函数中存在笔误:TypedTestDesc::Type应改为TypedTestDesc::TestTypeT(结构体TypedTestDesc中定义的类型别名是TestTypeT),修正后才能正常编译运行。

可在main函数中添加bar的调用测试:

int main()
{
  foo<TypedTestDesc<TestStruct>{"TestStruct"}>();
  bar<TypedTestDesc<TestStruct>{"TestStruct"}>();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 12:51:35