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])();
}