最近在学GP,有些许收获,记录一下,有错误还请有心人指出。C++ templates以其丰富的型别信息和运行期近零耗费而闻名,是一项很强大的型别技术,它可以使你的设计具有较好的扩展性和复用性。不过用的太多的话,编译时间有点长,所以诸如template template的不宜多用。
1. coding standard
这是我们小组使用的写码标准,它由Herb Sutter倡导。
- Classes, functions, and enumerated types look LikeThis.
- Variables and enumerated values look likeThis.
- Member variables look likeThis_.
- Template parameters are declared with class if they can be only a user-defined type, and with typename if they can also be a primitive type.
2. function templates
在编译期间,会发生实体化(instantiation),用具体型别(如int)来取代T ,即进行了参数推倒(argument deduction),但template function不存在自动型别转换。
可以通过制定型别来具现化function template
eg: IsEqual(2,2.0);//定义见下,输出结果为1
function templates可以被重载(overload),eg:
struct Stu { long no; std::string name;
friend bool operator==(const Stu& lv, const Stu& rv) { return lv.no == rv.no; } };
template<typename T> inline bool IsEqual(const T& lv, const T& rv) { return lv == rv; }
inline bool IsEqual(const Stu& lv, const Stu& rv) { return lv.no == rv.no; }
int main() { Stu a = {1,"daxi"}; Stu b = {2,"wang"}; //调用IsEqual(const Stu& lv, const Stu& rv),输出0
cout << IsEqual(a, b) << endl; //调用IsEqual(const T& lv, const T& rv) ,输出0
cout << IsEqual<>(a, b) << endl; return 0; }
|
注:编译器会优先选择non-template function
3. class templates
stl中的容器类大量运用了class template.
functor也用的比较多。
4. member templatesmember template 和 fuction template 类似,用途比较广泛。
5. an example
///类型选择器 template<bool isformer, typename T1, typename T2> struct IfElse { typedef T1 ResultType; };
///specialization template<typename T1, typename T2> struct IfElse<false, T1, T2> { typedef T2 ResultType; };
///类型提升器 template <typename T1, typename T2> struct TypePromotion
{ typedef typename
IfElse< (sizeof(T1) >= sizeof(T2)), T1, T2 >::ResultType ResultType; };
///specialization
template <typename T> struct TypePromotion<T, T> { typedef T ResultType; };
///简易计算器 struct Caculator { template<typename T1, typename T2> static typename TypePromotion<T1, T2>::ResultType Add(T1 a, T2 b) { return a + b; }
template<typename T1, typename T2> static typename TypePromotion<T1, T2>::ResultType Decrease(T1 a, T2 b) { return a - b; }
template<typename T1, typename T2> static typename TypePromotion<T1, T2>::ResultType Max(T1 a, T2 b) { return a < b ? b : a; }
template<typename T1, typename T2> static typename TypePromotion<T1, T2>::ResultType Multiply(T1 a, T2 b) { return a * b; } };
|
阅读(1531) | 评论(0) | 转发(0) |