C++类型判断小程序,错了不知道什么回事?

来源:百度知道 编辑:UC知道 时间:2024/07/01 07:03:49
#include <iostream.h>
template <class T>
int type(T n)
{
if(strcmp(T==int) return 0;
else if(T==char) return 1;
else if(T==double) return 2;
else return 3;
}
void main(void)
{
cout<<type(1)<<endl;
cout<<type('a')<<endl;
cout<<type(54.156)<<endl;
}
不知道为什么不能运行,怎样修改啊?

写法错了,模板T不能拿来这样用,应该是判断变量n的类型,而不是判断T是什么,n被T修饰,
type函数正确的写法应该是:

int type( T n )
{
if ( strcmp( typeid( n ).name( ), "int" ) == 0 )
{
return 0;
}
else if ( strcmp( typeid( n ).name( ), "char" == 0 )
{
return 1;
}
else if ( strcmp( typeid( n ).name( ), "double" == 0 )
{
return 2;
}
else
{
return 3;
}
}

if(strcmp(T==int) return 0;
else if(T==char) return 1;
else if(T==double) return 2;
else return 3;

不能这样判断!!!

将函数type()修改为如下形式:
template <class T> int type(T n)
{
if (typeid(T) == typeid(int))
{
return 0;
}
else if (typeid(T) == typeid(char))
{
return 1;
}
else if (typeid(T) == typeid(double))
{
return 2;
}
else
{
return 3;