template 疑
以下使用的class T,什要用class ,意思代表什
用typename也是一?,什它自int ,double ,char 三呢
是怎判的?
template < class T >
void printArray( const T *array, const int count )
{
for ( int i = 0; i < count; i++ )
cout < < array[ i ] < < " ";
cout < < endl;
} // end function printArray
int main()
{
const int aCount = 5, bCount = 7, cCount = 6;
int a[ aCount ] = { 1, 2, 3, 4, 5 };
double b[ bCount ] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
char c[ cCount ] = "HELLO "; // 6th position for null
cout < < "Array a contains: " < < endl;
// call integer function-template specialization
printArray( a, aCount );
cout < < "Array b contains: " < < endl;
// call double function-template specialization
printArray( b, bCount );
cout < < "Array c contains: " < < endl;
// call character function-template specialization
printArray( c, cCount );
return 0;
} // end main
[解决办法]
template < class T > <======这里的class 和typename等价,模板的基本语法,规定而已
void printArray( const T *array, const int count )
{
for ( int i = 0; i < count; i++ )
cout < < array[ i ] < < " ";
cout < < endl;
} // end function printArray
[解决办法]
编译的时候把类型匹配了进去,比如你的int,double什么的.它会为每个类型形成一段
代码,比如匹配int的时候,就会把你的模版函数中的T换成int,然后调用的时候编译
器调用这个方法.
关于class 和 typename都一样,如果你的编译器不识别class 就用typename
[解决办法]
template <class T> 等价于 template <typename T>
就是在说,在下面的程序里,T是一个类型,所以无所谓用哪个来表示了,都是一样的
[解决办法]
对于函数模板,你可以不显示指出模板参数类型,编译器可以根据你的实参类型推倒模板参数类型,进而实例化相应函数模板。
对于类模板,你必须显示指定模板参数类型。