1. 例子<link error>
//myfirst.h
template <typename T>
void print_typeof (T const&);
//myfirst.cpp
#include <iostream>
#include <typeinfo>
#include "myfirst.hpp"
// implementation/definition of template
template <typename T>
void print_typeof (T const& x)
{
std::cout << typeid(x).name() << std::endl;
}
//myfirstmain.cpp
#include "myfirst.hpp"
// use of the template
int main()
{
double ice = 3.0;
print_typeof(ice); // call function template for type double
}
链接出错!!实例化时,编译器要知道哪个定义以及基于那个模版实参进行实例化,这个例子里两部分信息分开.
1. 调用时没有看到基于 double的实例化,它假设在某处提供这个定义,产生了一个指向该定义引用。
2. 编译myfirst.cpp,他没有指出,编译器要基于特定实参所包含模板定义进行实例化!
//解决方法...
//myfirst2.h
#include <iostream>
#include <typeinfo>
// declaration of template
template <typename T>
void print_typeof (T const&);
// implementation/definition of template
template <typename T>
void print_typeof (T const& x)
{
std::cout << typeid(x).name() << std::endl;
}
//myfirst2.cpp
#include "myfirst2.hpp"
// using of template
int main()
{
double ice = 3.0;
print_typeof(ice); // call function template for type double
}
缺点:包含头文件带来开销!增加了编译复杂程序的时间与消耗!
总结:非内联函数模板与内联函数宏区别
1. 调用位置不进行扩展,调用时进行实例化!可能导致编译器在不同文件产生两个一样的拷贝!
2. 编译器来解决这个问题!!!