为什么这段符合C++20标准的代码在Clang上能编译,而在MSVC上却因为模板推导错误而编译失败?
我在研究C++20的 concepts,遇到了一个编译器实现上的差异。
这段代码在Clang 17和 GCC 13上可以编译,但MSVC(VS2022)却拒绝它:
template <typename T>
concept HasFoo = requires(T t) {
{ t.foo() } -> std::same_as<int>;
};
template <HasFoo T>
void callFoo(T t) {
std::cout << t.foo();
}
struct X {
int foo() const { return 42; }
};
int main() {
X x;
callFoo(x);
}
MSVC错误:
error C7602: 'callFoo': the associated constraints are not satisfied
为什么MSVC在这里会失败模板参数推导?这是一个已知的编译器错误(bug),还是我漏掉了某个微妙的规则?
解决方案
https://gcc.godbolt.org/z/Khc7dTrn8
这三个平台(最新版)在CE上似乎都能通过你的代码。所以也许可以考虑升级你的编译器?
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。