forked from PaddlePaddle/Paddle
    
        
        - 
                Notifications
    
You must be signed in to change notification settings  - Fork 0
 
CPP模板的实例化
        Qiao Longfei edited this page Feb 24, 2018 
        ·
        2 revisions
      
    并不一定一定要看到模板的具体定义,如果在调用的时候,看不到具体定义,会生成一个undefine的调用接口,在连接的时候来找到对应的实例化实现,对模板类和模板函数都是这样。
写一个文件 main.cpp
#include <iostream>
template<typename T> void test(T a);
int main() {
  test<int>(10);
}# gcc -c Only run preprocess, compile, and assemble steps
gcc -c main.cpp
上面这一步能生成一个正常的main.o,里边有一个符号
nm main.o
U void test<int>(int)
这个符号是未定义的,也就是编译的时候,模板不一定需要实例化,也可以只有一个接口。
但是如果进行链接的话,就会报错
gcc main.cpp
报错:
Undefined symbols for architecture x86_64:
  "void test<int>(int)", referenced from:
      _main in main-22388f.o
ld: symbol(s) not found for architecture x86_64
找不到符号void test<int>(int)。对于class,也有类似的现象。
template<typename T> void test(T a);
template<typename T>
class A {
 public:
  void aa();
};
int main() {
  test<int>(10);
  A<int> a;
  a.aa();
}