向前宣布模板化类型 [英] forward declaration of templatized type

查看:61
本文介绍了向前宣布模板化类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

正如大家所期望的那样,以下代码片段无法编译



Hello all,
just as everybody would expect following snippet does not compile

namespace NonTemplate{

  struct Unknown;

  struct AnyStruct{
    Unknown *p;
    AnyStruct(Unknown* p): p(p){}
    void doStuff(){ p->doStuff(); } // <-- error: use of undefined type 'NonTemplate::Unknown'
  };

  struct Unknown{
    void doStuff(){}
  };

}





但为什么会这样?



but why this does?

namespace Template {

  template<typename T> struct Unknown;

  template<typename T> struct AnyStruct {
    Unknown<T> *p;
    AnyStruct(Unknown<T>* p) : p(p) {}
    void doStuff() { p->doStuff(); } // <-- OK
  };

  template<typename T> struct Unknown {
    void doStuff() {}
  };
}





P.S.我尝试了VC6和VC2013。



P.S. I tried both with VC6 and VC2013.

推荐答案

不同之处在于,对于模板,编译器会在需要时生成代码!



在尝试解释语句之前,编译器不会读取整个代码:此时它只会知道它之前看到的类型和定义。因此,在你的第一个例子中,它不会知道staruct Unknown有一个叫做doStuff的函数()



然而在第二种情况下,编译器会看到一个模板类并尝试实例化该模板。由于它在命名空间模板范围内,它将扫描整个namescape以获取此模板的定义。



编译器在模板上的工作方式不同的原因是因为它必须!模板化代码仅在编译器找到实际实例化时实例化,因此没有安全的方法来确保以特定顺序解析所有相关模板定义。因此,编译器必须能够在整个代码中搜索模板定义,即使在尚未解析用于编译的代码中也是如此。
The difference is caused by the fact that for templates the compiler generates the code the moment it is needed!

The compiler doesn't read the entire code before trying to interpret a statement: at this point it will only know the types and definitions it has seen before. Therefore, in your first example, it will not know that the staruct Unknown has a function called doStuff()

In the second case however, the compiler sees a templated class and tries to instantiate that template. As it is scoped within the namespace Template, it will scan the entire namescape for the definition of this template.

The reason the compiler works differently on templates is because it must! Templated code is instantiated only when the compiler finds an actual instantiation, and therefore there is no safe way to ensure all relevant template definitions are parsed in a specific order. Therefore the compiler must be able to search the entire code for template definitions, even in code it hasn't parsed for compilation yet.


这篇关于向前宣布模板化类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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