在类模板的成员函数中使用不完整类型 [英] Using incomplete type in a member function of a class template

查看:57
本文介绍了在类模板的成员函数中使用不完整类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC(8.3,9.1),Clang(7、8)和MSVC(19.20)的不同之处在于它们编译以下代码的能力:

GCC (8.3, 9.1), Clang (7, 8) and MSVC (19.20) differ is their ability to compile this code:

struct C;

template<typename T> struct S {
    void foo() {
        // C2 c;
        C c;
    }
};

class C {};

int main() {
    S<int> s;
    s.foo();
    return 0;
}

GCC和MSVC接受,而Clang拒绝。即使我将 foo 本身作为模板和/或根本不调用它,Clang也会拒绝它。

GCC and MSVC accept it, whereas Clang rejects it. Clang rejects it even if I make foo itself a template and/or do not call it at all.

我的理解是,除非调用 foo ,否则不会实例化它,并且在它被实例化时将其实例化。叫做。那时 C 完成,并且代码应编译。

My understanding is that foo is not instantiated unless it is called, and it is instantiated at the point where it is called. At that point C is complete, and the code should compile. Is this a reasoning of GCC?

作为旁注,如果未调用 foo ,则MSVC接受代码即使我将 C 替换为 foo 中未声明的 C2 -在这种情况下,似乎只是检查函数体在语法上是否正确。

As a side note, if foo is not called, MSVC accepts the code even if I replace C with an undeclared C2 inside foo - in this case it seems to just check the function body to be syntactically correct.

根据标准哪个行为正确?如果是Clang,为什么标准会禁止GCC提供的灵活性?

Which behaviour is correct according to the Standard? If it is Clang's, why does the Standard forbids the flexibility that GCC gives?

推荐答案

这是格式错误的,不需要诊断,由于 [temp.res] / 8

This is ill-formed, no diagnostic required, due to [temp.res]/8:


该程序格式错误,无需诊断,如果:

The program is ill-formed, no diagnostic required, if:


  • [...]

  • 由于不依赖于模板参数或[..]的构造,紧随其定义的模板的假想实例化将不正确。 。]

  • [...]

所以整个程序很糟糕,但是不需要需要对其进行诊断。 Clang可以,这对clang很好,而gcc和MSVC却不可以,这没错。

So the whole program is bad, but implementations aren't required to diagnose it. Clang does, which is good for clang, gcc and MSVC don't, which isn't wrong.

这篇关于在类模板的成员函数中使用不完整类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆