本身未实例化的函数中的错误实例化。 clang 和 gcc 之间的行为差​​异

Bad instanition in function that is not itself instantiated. Difference in behaviour between clang and gcc

考虑以下 C++ 程序:

template<typename X>
struct S
{
    X x;
};

template<typename>
void f()
{
    S<void> s;
}

int main()
{
}

使用“-std=c++17 -pedantic-errors”编译时,clang 会出现编译错误,但 gcc 不会出现编译错误。

c++ 标准对这个程序有何规定?是否有效?如果它无效,它是否有未定义的行为?

如果回答此问题的人可以继续并在他们的答案中包含 c++ 标准的相关部分,那就太好了。

Compiler explorer link 试试看:https://godbolt.org/z/Ke1K7b

您的函数模板使程序成为 ill-formed,无需诊断。

[temp.res]

8 The validity of a template may be checked prior to any instantiation. [ Note: Knowing which names are type names allows the syntax of every template to be checked in this way. — end note ] The program is ill-formed, no diagnostic required, if:

  • no valid specialization can be generated for a template or a substatement of a constexpr if statement within a template and the template is not instantiated, or

无论您用什么实例化 f,都会导致无效声明。所以它与该段落匹配。

Clang 会立即检查,GCC 不会,但这两种方法同样有效。无论哪种方式,问题出在模板中的构造上,而不是编译器上。