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

模板参数对象的constexpr函数求值:MSVC与Clang/GCC兼容性问题

MSVC对C++20模板实参中成员函数调用的编译问题

以下代码符合C++20标准:

template<int i> struct A {};

struct B
{
  constexpr int one() const { return 1; }
};

template<B b> A<b.one()> f() { return {}; }

void test()
{
  f<B{}>();
}

但MSVC(包括Visual Studio 2022各版本,v19.28会触发内部编译器错误ICE)编译时会报以下错误:

error C2672: 'f': no matching overloaded function found
error C2770: invalid explicit template argument(s) for 'A<'function'> f(void)'

而Clang和GCC均能正常编译这段代码。

目前已找到两种可行的规避方案:

  • 用结构体包裹函数求值:
template<B b>
struct WrapOne
{
  static constexpr int value = b.one();
};

template<B b> A<WrapOne<b>::value> f() { return {}; }
  • 用inline constexpr变量包裹:
template<B b> inline constexpr auto one_v = b.one();
template<B b> A<one_v<b>> f() { return {}; }

我猜测这是MSVC的编译器bug,但尚未在微软开发者社区找到相关报告,想确认该问题是否确实是MSVC的bug,同时寻求其他更简洁巧妙的解决方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:36:27