【问题标题】:MSVC Bug? Overloaded member not found for constrained functionMSVC错误?未找到受约束函数的重载成员
【发布时间】:2021-02-07 14:46:57
【问题描述】:
此代码无法使用 MSVC 19.27.29112.0 编译,但适用于 GCC 10.2.0。在这两种情况下都启用了 C++20:
template <typename T>
struct Blah {
void blah() requires (sizeof(T) == 4);
};
template <typename T>
void Blah<T>::blah() requires (sizeof(T) == 4) {}
int main() {
Blah<int> b;
b.blah();
return 0;
}
错误 C2511: 'void Blah::blah(void)': 在 'Blah' 中找不到重载的成员函数
仅当requires 依赖于类的模板类型时才会发生错误。例如,requires (sizeof(int) == 4) 工作正常。将blah() 转换为模板函数并执行requires (sizeof(U) == 4) 之类的操作也可以。
谁能确认这是一个编译器错误?
【问题讨论】:
标签:
c++
visual-studio
language-lawyer
c++20
【解决方案1】:
(评论太长了。)这看起来确实是一个错误,我建议你正式report it。
奇怪的是,以下是可行的。
template <typename T>
struct Blah {
enum { sizeofT = sizeof(T) }; // or: static const size_t sizeofT = sizeof(T);
// or: static constexpr size_t sizeofT = sizeof(T);
void blah() requires (sizeofT == 4);
};
template <typename T>
void Blah<T>::blah() requires (sizeofT == 4) {}
int main() {
Blah<int>().blah(); // ok
Blah<float>().blah(); // ok
// Blah<short>().blah() // c7500: 'blah': no function satisfied its constraints
// Blah<double>().blah(); // c7500: 'blah': no function satisfied its constraints
return 0;
}
【解决方案2】:
显然,gcc 和 clang 知道您的代码中存在的重载 (here)。但是,与 gcc 和 clang 相比,我认为 MS 编译器团队会在不同的阶段对内存初始化模块进行流水线处理。我(有点)推测这是因为以下代码有效(即,在结构模板本身中为 blah() 函数初始化和创建内存):
template<typename T>
struct Blah {
void blah() requires (sizeof(T) == 4) {};
};
int main() {
Blah<int> b;
b.blah();
}