模板参数对象的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
相关产品推荐
相关产品推荐

