当我使用最新的 Visual Studio 编译以下代码时,编译成功。
class C;
class T
{
public:
template<typename A>
void f();
private:
C* c;
};
int main()
{
T t;
t.f<int>();
}
template<typename A>
void T::f()
{
this->c->g();
}
class C
{
public:
void g() {}
};
但是当我删除
this->
来自 this->c->g()
, 编译失败 C2027: use of undefined type 'C'
.当我制作方法时
f
非模板,无论如何编译失败this->
存在与否,所以我认为这与模板编译/实例化有关,但我无法弄清楚。我已阅读 this answer ,但不是 c
和 g
明确在 T::f()
?所以,问题是:
this->
的作用是什么|这里? 编译器差异:
+-----------------------+---------------------+----------------------+--------------+
| | Template, w/ this-> | Template, w/o this-> | Non-Template |
+-----------------------+---------------------+----------------------+--------------+
| Visual Studio 16.3.10 | Success | Fail | Fail |
| x64 msvc v19.24 | Success | Success | Fail |
| x86-64 gcc 9.2 | Success w/ warning | Success w/ warning | Fail |
| x86-64 clang 9.0.0 | Fail | Fail | Fail |
+-----------------------+---------------------+----------------------+--------------+
x64 msvc v19.24
, x86-64 gcc 9.2
和 x86-64 clang 9.0.0
使用 Compiler Explorer 进行测试。
最佳答案
由于 C++17 [temp.res]/8.3,该程序格式错误:
The program is ill-formed, no diagnostic required, if:
- [...]
- a hypothetical instantiation of a template immediately following its definition would be ill-formed due to a construct that does not depend on a template parameter,
假设的实例是格式错误的,因为
c->g
用于 c
具有指向不完整类型的指针,并且不受模板参数 A
的影响.因此,是否引发错误是一个实现质量问题。
关于c++ - 模板方法访问前向声明的类无法在没有此指针的情况下编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60215335/