typedef 与 typename 的用法

一、typedef:类型说明

类型说明的格式为:
typedef 类型 新定义名;
类型说明只定义指定的一个类型的新名字,并不是定义一种新的数据类型。

eg:
typedef int INT;
这样声明后就可以用int的别名INT来定义新的对象
INT i,j;

typedef同样可以用来说明结构体、联合、枚举、类。
说明一个结构体的格式为:

typedef struct
{
   数据类型  成员名;
   数据类型  成员名;
   ...
}结构体名;

这样就直接可以用结构体名定义结构变量了eg:

    typedef struct
    {
        char name[8];
        int age;
        string num;
        float math,phys,chem,engl,biol;
    }student;
    student Mahua;//新定义的结构体对象Mahua

二、typename:类型解释

typename 关键字告诉编译器把它后面的内容解释成一个类型,以下情况必须对一个name使用typename关键字;

1. 一个唯一的name(可以作为类型理解),它嵌套在另一个类型中。
2. 依赖于一个模板参数,就是说:模板参数在某种程度上包含这个name,当模板参数使编译器在指认一个类型时产生了误解。(编译器可能把一个类型当成了一个变量)此时为了避免这样的误解,我们应该加上typename,此时编译器就知道他是一个类型,可以用来声明并创建实例。

eg:

    #include<iostream>
    #include<typeinfo> //for typeid() operator
    //typeid()是一个操作符,为了获取一个变量的具体类型
    using namespace std;
    template<typename TP>
    struct COne
    {
        //default member is public of C++
        typedef TP one_value_type;
    };
    template<typename COne>//用一个模板类名作为模板参数
    struct CTwo
    {
        //1.
        //typedef COne::one_value_type two _value_type;
        //2.
        typedef typename COne::one_value_type  two_value_type;
    };  
    /*
     以上两个类只是定义了两个内部的public类型,但注意第二个类CTwo的two_value_type类型,依赖COne的one_value_type,而后者又取决于COne模板类实例化时传入的参数类型。
    */
    int main()
    {
        typedef COne<int> OneInt_type;
        typedef CTwo<OneInt_type> TwoInt_type;
        TwoInt_type::two_value_type i;
        int j;
        if(typeid(i) == typeid(j))//如果i 是int型变量
        {
          cout<<"Right"<<endl;
        }
        return 0;
    }
    //结果打印Right

使用typename来代替class :这样可以增加程序的清晰度

template<typename T> class X{};
int main()
{
    X<int> x;
}

你当然也会看到许多类似的代码没有使用typename关键字,因为模板概念诞生之后很久了,才有了typename关键字的加入。
用typename自定义一个类型
要知道typename关键字不会自动的typedef,
typename Seq::interator it;
只是声明了一个Seq::iterator 类型的变量,如果你想定义一个新类型的话,你必须这样:typedef typename Seq::iterator it;

另外这里关于其他typename用法的解释如下:
问题:
在下面的template declarations(模板声明)中class和typename有什么不同?

template class Widget;//uses "class"
template class Widget;//uses "typename"
答案:没什么不同。在声明一个template typeparameter(模板类型参数)的时候,classtypename 意味着完全相同的东西。用typename暗示着这个参数不必要是一个class type(类类型)
然而,C++并不总把classtypename视为等同的东西。有时你必须使用typename。为了理解这一点,我们不得不讨论你会在一个template(模板)涉及到的两种名字。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值