GeekBand笔记: C++面向对象高级编程(4)

2016-03-31  本文已影响0人  Royye

Templates and Generic Programming

模板 template

函数模板(function template)

template<template parameter list>
template<typename T1, typename T2>

函数模板实例化 instantiate

When the compiler instantiates a template, it creates a new “instance” of
the template using the actual template argument(s) in place of the
corresponding template parameter(s).

非类型模板参数(nontype parameter)

template <unsigned N, unsigned M>
inline int compare(const char (&p1)[N], const char (&p2)[M]) {
    return strcmp(p1, p2);
};

// 非类型模板参数的模板实参必须是常量表达式
cout << compare("a", "ba") << endl;

类模板(class template)

类模板的实例化

Blob<int> ia;
Blob<int> ia2 = {0, 1, 2, 3, 4};
Blob<int> ia2 = {0, 1, 2, 3, 4}; // 类模板实例化
ia2.size(); // 实例化 Blob<int>::size() const
上一篇下一篇

猜你喜欢

热点阅读