MSVC拒绝C++23多参数operator[]模板实现,是否为编译器Bug?
C++23多参数
operator[]在MSVC 17.12.3中的编译问题 最小化测试代码
struct Context { template<class T> int operator[](int, T) { return 0; } }; int main() { Context ctx; return ctx[0, 0]; }
问题描述
上述代码符合C++23标准规范,可在最新版本的GCC和Clang编译器中正常编译通过,但在**MSVC 19.42.34435(对应Visual Studio 17.12.3)**下编译失败。
MSVC报错信息
1>test.cpp(15,20): error C2676: binary '[': 'Context' does not define this operator or a conversion to a type acceptable to the predefined operator 1> test.cpp(6,27): 1> could be 'int Context::operator [](int,T)' 1> test.cpp(15,12): 1> 'initializing': cannot convert from 'Context' to 'int' 1> test.cpp(15,12): 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
分析与结论
MSVC对C++23多参数operator[]的支持是从Visual Studio 17.12版本开始新增的,但从当前报错来看,编译器在处理带模板参数的多参数operator[]时存在逻辑错误:明明找到了匹配的重载候选,却错误地尝试将Context对象转换为int,最终判定无法匹配运算符。
这属于MSVC的编译器实现Bug,你可以放心向微软提交Bug报告。
内容的提问来源于stack exchange,提问作者prapin
相关产品推荐
相关产品推荐

