Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusions around explicit template instantiation

Well, I think I just get extremely confused by explicit template instantiation ~>_<~

  1. Could an explicit instantiation declaration exploit an implicit instantiation definition?
  2. What if both explicit and implicit instantiation definitions exist in a program? Will they ultimately collapse into a single one?
  3. Does an explicit instantiation declaration have any effect when placed after an implicit instantiation definition?

Also, see the following code:

#include <iostream>
#include <vector>

std::vector<int> a;  // Implicit instantiation definition.

// Explicit instantiation declaration.
extern template class std::vector<int>; 

int main() {
  std::cout << std::vector<int>().size();  // So what?
}

It causes the link error

/tmp/ccQld7ol.o: In function `_GLOBAL__sub_I_a':
main.cpp:(.text.startup+0x6e): undefined reference to `std::vector<int, std::allocator<int> >::~vector()'
collect2: error: ld returned 1 exit status

with GCC 5.2, but builds fine with clang 3.6. Which one is correct according to the standard?

I hope there is an insightful way to understand explicit template instantiation so that answers to all the questions above can be logically deduced and explained.

like image 367
Lingxi Avatar asked Apr 15 '26 00:04

Lingxi


1 Answers

[temp.explicit]/p11:

An entity that is the subject of an explicit instantiation declaration and that is also used in a way that would otherwise cause an implicit instantiation (14.7.1) in the translation unit shall be the subject of an explicit instantiation definition somewhere in the program; otherwise the program is ill-formed, no diagnostic required.

like image 90
T.C. Avatar answered Apr 16 '26 14:04

T.C.