缺少了C++模板真的不行吗
首次进行C++的初始学习时,首先接触到的就是C++模板,在创建C++模板时出现了一些困难和难以理解的地方,比如向上类型转换,向下类型转换等相关麻烦,对于除类型之外,其余都相同的函数,我们一般有3种解决办法。
1、针对每个不同的类型重复地编写函数实体(C语言的做法):
T const& f(T const& a, T const& b)
{
return a + b; //1处
}
int g = f(1,2); 2、使用Object(Java的做法)或者void*缺点有两个效率问题方面也有问题类型检查问题
3、使用宏预处理机制
缺点:只是愚蠢的文本替换,而且也不会考虑作用域和类型安全。然而,应用C++模板却可以避免这些缺点,我们可以编写:
优点:
代码简洁优雅,所有参数类型都以T来代替,真正实现了类型无关性。更好的类型安全性,所有的类型检查都是在编译期进行,而且避免使用指针。不存在继承,效率高。(1)没有虚函数;(2)所有的一切工作都是在编译期完成,大大提高运行效率。目的:告诉编译器如何做出最佳的选择,而且这种选择全部是在编译期完成的。C++模板的机制:特化 和 实参演绎
// traits/accumtraits3.hpp
template
lass AccumulationTraits;
c template<>
class AccumulationTraits {
public:
typedef int AccT;
static AccT const zero = 0;
};
template<>
class AccumulationTraits {
public:
typedef int AccT;
static AccT const zero = 0;
};
template<>
class AccumulationTraits {
public:
typedef long AccT;
static AccT const zero = 0;
};
(2)policy:通常表现为某个函数,指定的是一种行为
class SumPolicy {
public:
template
static void accumulate (T1& total, T2 const & value) {
total += value;
}
};
(3)trait和policy的用法:
template >
class Accum {
public:
typedef typename Traits::AccT AccT;
static AccT accum (T const* beg, T const* end) {
AccT total = Traits::zero();
while (beg != end) {
Policy::accumulate(total, *beg);
++beg;
}
return total;
}
}; 相关推荐
IT之家 2020-03-11
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20