简体   繁体   English

未实例化未定义的 class 模板以检查友元函数

[英]Undefined class template is not instantiated to check for friend functions

The following program compiles (see on godbolt ), but it would not compile if we uncommented the definition of Buffer .以下程序可以编译(参见godbolt ),但如果我们取消注释Buffer的定义,它将无法编译。

template <int size>
struct Buffer /*{ char buf[size]; }*/;

template <class T>
struct Wrapper { void operator+() {} };

Wrapper<Buffer<-5>> a;

void f() { +a; }

The reason, the uncommented version does not compile: +a triggers ADL, and to collect all candidates for operator+ , all associated classes must be checked for friend functions.原因,未注释的版本无法编译: +a触发 ADL,并且要收集operator+的所有候选者,必须检查所有关联的类是否有friend函数。 Buffer<-5> is an associated class, so it must be instantiated. Buffer<-5>是关联的 class,因此必须对其进行实例化。 Instantiation fails, hence the compilation error.实例化失败,因此编译错误。 See this question .看到这个问题

I wonder if Buffer<-5> must be instantiated, why don't we have a compilation error, if Buffer is not defined?我想知道是否必须实例化Buffer<-5> ,如果未定义Buffer ,为什么我们不会出现编译错误?

You can (implicitly) instantiate a class template from only a declaration;可以(隐式)仅从声明中实例化 class 模板; you get an incomplete class type, just like from struct A;你得到一个不完整的 class 类型,就像从struct A; ( [temp.inst]/2 ). ( [temp.inst]/2 )。 It's not an error, of course, to do ADL with an incomplete associated class;当然,使用不完整的关联 class 执行 ADL 不是错误; the class in question is simply not searched for friend declarations.有问题的 class 根本没有搜索朋友声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM