1,为了简化,清晰。比如,
vector<list<int *>*> temp(10);
可以简化为
typedef list<int *> listnum;
typedef vector<listnum *> vectornum;
vectornum temp(10);
2,定义指向成员的指针。
class A{
virtual sup() = 0;
}
typedef void (A::* pt)();
void f(A *a)
{
pt ptemp = &A::sup;
}
typename:
template的含义有两个:
1)typename var_name;表示var_name的定义还没有给出,这个语句通常出现在模版的定义内,例如:
template <class T>
void f() {
typedef typename T::A TA; // 声明 TA 的类型为 T::A
TA a5; // 声明 a5 的类型为 TA
typename T::A a6; // 声明 a6 的类型为 T::A
TA * pta6; // 声明 pta6 的类型为 TA 的指针
}
因为T是一个模版实例化时才知道的类型,所以编译器更对T::A不知所云,为了通知
编译器T::A是一个合法的类型,使用typename语句可以避免编译器报错。
2)template < typename var_name > class class_name; 表示var_name是一个类型,
在模版实例化时可以替换任意类型,不仅包括内置类型(int等),也包括自定义类型class。
这就是问题中的形式,换句话说,在template<typename Y>和template<class Y>中,
typename和class的意义完全一样。
class A; // let compiler know A is a class here. i may define it later.
typedef A A_type; // ok
typedef A::B AB_type; // error. the compiler doesn't 'B' is a type or something else.
typedef typename A::B AB_type; // ok. you tell the compiler B is really a type, so it will not complain.
class A {
public:
typedef int B; // i kept my promise to really define 'B' as type here.
...
};
typedef orgtype newtype
当orgtype编译器不知道是一种类型时,用:
typedef typename orgtype newtype
最常见的用法是,在类里面typedef了一个newtype,在另一个地方使用时。
typedef 最复杂的用法就是定义函数指针,举下面的例子:
#include <iostream.h>
#include <stdlib.h>
extern void func1(); // Declare 4 functions.
extern void func2(); // 在别的地方定义
extern void func3();
extern void func4();
typedef void (*pvfn)(); // function that takes no arguments
// and returns type void.
void main( int argc, char * argv[] )
{
// Declare an array of pointers to functions.
pvfn pvfn1[] = { func1, func2, func3, func4 };
// Invoke the function specified on the command line.
if( argc > 0 && *argv[1] > '0' && *argv[1] <= '4' )
(*pvfn1[atoi( argv[1] ) - 1])();
}