C++中确定型别

来源:互联网 发布:只进入身体知乎 编辑:程序博客网 时间:2024/06/06 03:42
#include<iostream>using namespace std;template<typename T>struct Iter{typedef T value_type;T* ptr;Iter(T* p=0):ptr(p){}T& operator*() const {return *ptr;}};template<class I>typename I::value_type //这一整行是func的返回类型
func(I item){return *item;}int main(){Iter<int> t(new int(10));cout<<func(t)<<endl;int *tt;tt=new int(10);cout<<*tt<<endl;cout<<tt<<endl;return 0;}

定义了一个Iter类,其中的typedef T value_type 是内嵌型别声明。

注意typename I::value_type是函数func的返回类型,且必须要typename这个关键字。

因为T是一个template参数,在他被编译器具体化之前,编译器对T一无所悉。换句话说就是编译器姿势不知道Iter<T>::value_type代表的是一个型别

或是一个member function或是一个data member。关键字typename的用意在于告诉编译器这是一个型别,如此才能顺利通过编译

原创粉丝点击