以下代码无法在所有 gcc 10.1、msvc 19.24 和 clang 10.0.0 中编译:
template <int N>
struct A {
void g() requires (N == 3) {}
void f() requires (N == 3) { g(); }
};
template struct A<2>;
错误是这样的error C7500: 'g': no function satisfied its constraints
我对此感到有些惊讶。这是否按预期工作,是编译器中的缺陷,还是标准中的缺陷?我希望这样的 requires 语句为我提供成员函数,这些函数有条件地存在于模板参数的值中。解决方法如下:
template <int N>
struct A {
void g() requires (N == 3) {}
template <bool = true>
void f() requires (N == 3) { g(); }
};
template struct A<2>;
它按预期编译,但引入了一个无关的模板参数,其唯一目的是防止实例化。
最佳答案
这似乎是编译器中的一个错误;我为所有三个编译器报告了它。 Visual Studio最近在 16.7 Preview 1 中修复了这个问题。Gcc开发人员一致认为这是一个错误。目前还没有关于 Clang 的消息。
关于c++ - 约束和显式模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62845666/