首页 > 学院 > 开发设计 > 正文

经典问题解析(4)

2019-11-06 09:02:04
字体:
来源:转载
供稿:网友

typename 代替 class 表示泛型

在阅读代码的过程中,会发现如下的用法:

这里写图片描述 在上面的程序中,采用关键字class来表示泛型编程,这是早期的C++的用法,当然,现在需要使用typename。

举例,分析程序:

#include <cstdlib>#include <iostream>using namespace std;template<typename T, int N>//类模板,定义了一个类 class Test{public: typedef T ElemType; //在类中还定义了一个新的类型 //enum { LEN = N }; static const int LEN = N; ElemType array[LEN];//这个新的类型作用范围在这个类中 };template<typename T> //定义的一个函数模板,注意这个不是成员函数 void test_copy(T& test, typename T::ElemType a[], int len)// typename T::ElemType 表示定义的数据类型,必须加上typename,表明这是类型不是成员变量 // 这两个模板各自的 T 表示的含义不同 { int l = (len < T::LEN) ? len : T::LEN; for(int i=0; i<l; i++) { test.array[i] = a[i]; }}int main(int argc, char *argv[]){ Test<int, 5> t1; Test<float, 3> t2; int ai[] = {5, 4, 3, 2, 1, 0}; float af[] = {0.1, 0.2, 0.3}; test_copy(t1, ai, 6); test_copy(t2, af, 3); for(int i=0; i<5; i++) { cout<<t1.array[i]<<endl; } for(int i=0; i<Test<float, 3>::LEN; i++) { cout<<t2.array[i]<<endl; } cout << "PRess the enter key to continue ..."; cin.get(); return EXIT_SUCCESS;}

注意,在上面的程序中,函数模板的第二个参数前面,一定要加上typename,来表示这是一个类型。

面试题

写函数判断一个变量是否为指针。

函数模板与可变参数函数可以组合进行应用。

解决方案1:

#include <cstdlib>#include <iostream>using namespace std;template<typename T> //函数模板 bool isPtr(T*){ return true;}bool isPtr(...) //可变参数 { return false; }int main(int argc, char *argv[]){ int* pi = NULL; float* pf = NULL; int i = 0; int j = 0; cout<<isPtr(pi)<<endl; cout<<isPtr(pf)<<endl; cout<<isPtr(i)<<endl; cout<<isPtr(j)<<endl; cout << "Press the enter key to continue ..."; cin.get(); return EXIT_SUCCESS;}

方案1已经可以解决问题,但是需要函数调用,希望再更高效一点。

解决方案2:采用宏定义

#include <cstdlib>#include <iostream>using namespace std;template<typename T>char isPtr(T*);//函数模板,没有函数体,返回为char int isPtr(...);//可变参数函数,没有函数体,返回为int #define ISPTR(v) (sizeof(isPtr(v)) == sizeof(char))//采用宏定义 int main(int argc, char *argv[]){ int* pi = NULL; float* pf = NULL; int i = 0; int j = 0; cout<<ISPTR(pi)<<endl; cout<<ISPTR(pf)<<endl; cout<<ISPTR(i)<<endl; cout<<ISPTR(j)<<endl; cout << "Press the enter key to continue ..."; cin.get(); return EXIT_SUCCESS;}
上一篇:开篇摘要总结

下一篇:在线学习

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表