c++ - 模板方法访问前向声明的类无法在没有此指针的情况下编译

标签 c++ templates this language-lawyer forward-declaration

当我使用最新的 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 ,但不是 cg明确在 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.2x86-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/

相关文章:

c++ - 如何使用外部模板

visual-studio-2010 - 在项目模板中使用 IWizard 而不在 GAC 中安装程序集?

c++ - 错误 : no type named 'value_type' in 'class boost::shared_ptr<const pcl::PointCloud<pcl::PointXYZ>>'

javascript - this.form 没有在 JavaScript 函数中传递表单

c++ - 如何替换版本 g++5 的 bvector header

c++ - 在构造函数初始值设定项中初始化非常量类型时出错?

c++ - 指针和字符串文字

c++ - 为什么这个模板不能编译?

javascript - 我想在 jQuery 上获取 $(this) 内元素的文本内容

java - C1.bar()执行了,不应该是C2.bar吗?