实例化澄清点

问题描述 投票:1回答:1

请考虑以下代码,取自https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.cbclx01/name_binding.htm

#include <iostream>
using namespace std;

void f(double) { cout << "Function f(double)" << endl; }

template <class A> struct container{ // point of definition of container
   void member1(){
      // This call is not template dependent, 
      // because it does not make any use of a template parameter.
      // The name is resolved at the point of definition, so f(int) is not visible.
      f(1); 
   }
   void member2(A arg);
};

void f(int) { cout << "Function f(int)" << endl; }

void h(double) { cout << "Function h(double)" << endl; }

template <class A> void container<A>::member2(A arg){ 
   // This call is template dependent, so qualified name lookup only finds
   // names visible at the point of instantiation.
   ::h(arg);  
}

template struct container<int>; // point of instantiation of container<int>

void h(int) { cout << "Function h(int)" << endl; }

int main(void){   
   container<int> test;   
   test.member1();
   test.member2(10);
   return 0;
}

输出是

Function f(double)
Function h(double)

文章指出,我理解这一点,但我不明白

模板的实例化点位于包含其使用的声明之前。在此示例中,容器的实例化点是显式实例化的位置

...这就是为什么当我将void h(int)的定义移动到被标记为实例化的点之上时,h(int)仍然没有被调用。当我将它移动到函数void container<A>::member2(A)的定义之上时,它才被调用。

在VS2017和g ++中就是这种情况,所以很明显文章措辞不好或者我遗漏了一些东西。有人可以澄清一下吗?

c++ templates instantiation
1个回答
0
投票

好的,上面发布的链接(point of instantiation and name binding)最终确实回答了这个问题,但它并不是那么清楚。我找到了this pagethis page,这进一步帮助了我的理解,因此我将它们发布在这里,以便其他人可以受益。

© www.soinside.com 2019 - 2024. All rights reserved.