第1个回答 2007-05-19
template<class T>是模版类的定义,其中T为动态运行时的类型,也就是在编译时不知道是什么类型,只有在程序运行时才会知道..
template<class T>
class Data { //类名
//....
};
你只要把data与func()放在类中就可以了...
第2个回答 2019-05-28
楼上正好说反了,模板的特性是静态多态,是编译时期的多态,比如:
template<classT>
voidfun(){}
fun(1);
fun(2.3);
编译器就只会给你生成个voidfun<int>()和voidfun<double>(),这种检查是在编译时期进行的.
比如用这一特性来搞个compiletimecheck,也叫staticcheck,比如mordenC++design上的:
template<bool>
structstatic_assert;
template<>
structstatic_assert<true>{};
就可以实现编译期间的assert;
static_assert<1>2>();
static_assert<2<3>();
摸板现在不支持实现和原型分开,所以你只能把他们放在同一个文件中,比如:
template<classT>
voidfun();
template<classT>
voidfun(){...}
或者直接
template<classT>
voidfun(){...}
我直接给你做个示范算了,比如写个求平方的模板:
//fun.cpp
template<classT>
Tsquare(Tx)
{
returnx*x;
}
//main.cpp
#include<iostream>
template<classT>
Tsquare(T);
intmain()
{
std::cout<<square(2);
}
或者
//fun.h
template<classT>
Tsquare(Tx){returnx*x;}
//main.cpp
#include<iostream>
#include"fun.h"
intmain()
{
std::cout<<square(2);
}