template<class T>可用来定义模板,为何还要引入typename?
类中定义新类型
5
2 3
Sub()
Hello World
——/类模板中定义新类型
C++编译器匹配调用优先级:①重载函数②函数模板③可变参数函数
类中定义新类型
class Test //一个类某种程度上可看做一namespace
{
public:
typedef int* PINT;
struct Point
{
int x,y;
};
class Sub
{
public:
Sub()
{
cout<<"Sub()"<<endl;
}
void print()
{
cout<<"Hello World"<<endl;
}
};
};
int main(int argc, char *argv[])
{
Test::PINT pi = new int(5);
cout<<*pi<<endl;
Test::Point po = {2,3};
cout<<po.x<<" "<<po.y<<endl;
Test::Sub sub;
sub.print();
delete pi;
return 0;
}
结果:
5
2 3
Sub()
Hello World
——/类模板中定义新类型
template<class T, int N>
class Test
{
public:
typedef T ElemType;
ElemType array[N];
};
template<class T>
void test_copy(T& test, T::ElemType*a, int len)
{ //报错,T::ElemType is not a type
//因编译器默认将ElemType当做静态成员变量而非类型
//该二义性导致typename的出现
//改错typename T::ElemType明确告诉编译器为类型
//应始终使用typename
for(int i=0; i<len; i++)
{
test.array[i] = a[i];
}
}
int main()
{
Test<int, 5> t1;
int ai[] = {5, 4, 3, 2, 1};
test_copy(t1, ai, 5);
for(int i=0; i<5; i++)
{
cout<<t1.array[i]<<endl;
}
return 0;
}
——/
C++编译器匹配调用优先级:①重载函数②函数模板③可变参数函数
int test(int i, int j)
{
cout<<"int test(int i, int j)"<<endl;
}
template<typename T>
T test(T i, T j)
{
cout<<"T test(T i, T j)"<<endl;
}
int test(...)
{
cout<<"int test(...)"<<endl;
}
int main()
{
int i = 0,j = 0;
test(i, j);
return 0;
}
——/写函数判断一变量是否为指针?
template<typename T>
void isPtr(T*)
{
cout<<"void isPtr(T*)"<<endl;
}
void isPtr(...)
{
cout<<"void isPtr(...)"<<endl;
}
int main()
{
int* pi = NULL;
int i = 0;
isPtr(pi);
isPtr(i);
return 0;
}
——/
template<typename T>
char isPtr(T*);
int isPtr(...);
#define ISPTR(v) (sizeof(isPtr(v)) == sizeof(char))
int main()
{
int* pi = NULL;
int i = 0;
cout<<ISPTR(pi)<<endl; //编译结束即确定,效率更高
cout<<ISPTR(i)<<endl;
return 0;
}