C++模板(Templates)

模板(template)是泛型编程的基础,"泛型"的含义就是没有不依赖具体的数据类型.模板的引入是为了创建一般性的类(模板类)或者函数(模板函数).典型的容器比如迭代器/算法等是泛型编程的典型案例.例如,定义了一个vector,可以使用vector<int>, vector<string>, vector<vector>等等.

函数模板

模板函数的一般定义方式为: 这里的type可以看做是代表了一种数据类型的占位符名称, 在函数内部的定义中可以使用它.

template <class type> ret-type func-name(parameter list){
      // body of function
}

举例分析如下. 注意, typename关键词和class关键词的作用是相同的,class关键词会让你产生是否定义的type只能是类,而不能是其他的数据类型? 为了避免这个歧义,这里引入了typename!!!

 1 #include <iostream>
 2 #include <string>
 3
 4 using namespace std;
 5
 6 template <typename T>
 7 inline T const& Max (T const& a, T const& b){
 8     return a < b ? b:a;
 9 }
10
11 int main() {
12
13     int i = 39;
14     int j = 20;
15     cout << "Max(i, j)" << Max(i, j) << endl;    # Max(i,j): 39
16
17     double f1 = 13.5;
18     double f2 = 20.7;
19     cout << "Max(f1, f2)" << Max(f1, f2) << endl;  # Max(f1, f2): 20.7
20
21     string s1 = "Hello";
22     string s2 = "World";
23     cout << "Max(s1, s2)" << Max(s1, s2) << endl;   # Max(s1, s2): World
24
25     return 0;
26
27 }

类模板

就像我们定义函数模板一样, 这里也可以定义类模板. 声明类模板的一般形式为:

template <class type>
class class-name{

}

举例:

#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>

using namespace std;

template <class T>
class Stack {
   private:
      vector<T> elems;     // elements 

   public:
      void push(T const&);  // push element
      void pop();               // pop element
      T top() const;            // return top element
      bool empty() const{       // return true if empty.
         return elems.empty();
      }
}; 

template <class T>
void Stack<T>::push (T const& elem) {
   // append copy of passed element
   elems.push_back(elem);
} 

template <class T>
void Stack<T>::pop () {
   if (elems.empty()) {
      throw out_of_range("Stack<>::pop(): empty stack");
   }

   // remove last element
   elems.pop_back();
} 

template <class T>
T Stack<T>::top () const {
   if (elems.empty()) {
      throw out_of_range("Stack<>::top(): empty stack");
   }

   // return copy of last element
   return elems.back();
} 

int main() {
   try {
      Stack<int>         intStack;  // stack of ints
      Stack<string> stringStack;    // stack of strings 

      // manipulate int stack
      intStack.push(7);
      cout << intStack.top() <<endl;   // 7

      // manipulate string stack
      stringStack.push("hello");
      cout << stringStack.top() << std::endl;   // hello
      stringStack.pop();
      stringStack.pop();
   }catch (exception const& ex) {
      cerr << "Exception: " << ex.what() <<endl;  // Exception: Stack<>::pop(): empty stack
      return -1;
   }
} 

参考:

[1] C++ Templates: https://www.tutorialspoint.com/cplusplus/cpp_templates.htm

时间: 2024-08-28 07:41:40

C++模板(Templates)的相关文章

C++ 高级篇(一)—— 模板(Templates)

模板(Templates)是ANSI-C++ 标准中新引入的概念.如果你使用的 C++ 编译器不符合这个标准,则你很可能不能使用模板. 函数模板( Function templates) 模板(Templates)使得我们可以生成通用的函数,这些函数能够接受任意数据类型的参数,可返回任意类型的值,而不需要对所有可能的数据类型进行函数重载.这在一定程度上实现了宏(macro)的作用.它们的原型定义可以是下面两种中的任何一个: template <class identifier> functio

AS 代码模板 文件模板 Templates

修改 File and Code Templates Settings –> Editor –>[File and Code Templates] 或者在右键new时选择子菜单[Edite File Templates...] 添加.修改文件模板 Files –> [Files],可用来修改.添加新建某类型文件(比如Class.Interface.C++)时的文件模板 此文件保存位置[C:\Users\Administrator\.AndroidStudio2.3\config\file

simple_form模板templates

通过新建lib/templates/erb/scaffold/_form.html.erb,来重写scaffold生成view下_form.html.erb的默认模板 Bootstrap: Basic Form: <%%= simple_form_for(@<%= singular_table_name %>) do |f|%> <%%= f.error_notification%> <div class="col-md-6"> <

zabbix模板(Templates)

模板是一些列配置的集合,它可以方便地快速部署在某监控对象上,并支持重复应用 这些对象包括: items triggers graphs applications screens(since Zabbix 2.0) low-level discovery rules(since Zabbix 2.0) 将模板应用至某主机上时,其定义的所有条目都会自动添加 模板的另一个好处在于,必要时,修改了模板,被应用的主机都会相应的作出修改 在Configuration-->Templates里可以看到系统内建

明明白白:python网站设计框架django的模板templates路径的最终解决方法

一个提示 SyntaxError: EOL while scanning string literal :反斜杆错误 \\ 不是 \ 我的mysite工程的整个目录: C:\web\mysite>tree /F 卷 C 的文件夹 PATH 列表 卷序列号为 00000200 0007:9B9B C:. │  db.sqlite3 │  manage.py │ ├─blog │  │  admin.py │  │  admin.pyc │  │  forms.py │  │  forms.pyc

Django学习案例一(blog):三.模板Templates

1.优化url配置 (1)上一节url配置用的是其中一种方式"Function views",本节进行优化,用"Including another URLconf"方式. Myblog/urls.py内容 from django.conf.urls import url,include #此处添加include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.ur

django-5.模板templates

前言 html是一个静态的语言,里面没法传一些动态参数,也就是一个写死的html页面.如果想实现在一个固定的html样式,传入不同的参数,这就可以用django的模板传参来解决. 模板参数 先在hello应用下新建一个templates文件夹,层级目录如下 └─helloworld │ db.sqlite3 │ manage.py │ __init__.py │ ├─hello │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ vie

django中将settings中全局变量应用于模板templates中

以项目名dispy为例,把站点名变量应用于模板中 ⑴ 在项目目录下创建dispy/global_settings.py文件 from django.conf import settings def get_global_settings(request): context = { 'site_name': settings.SITE_NAME, 'site_short_name': settings.SITE_SHORT_NAME, } return context ⑵ 在setting.py中

Django的模板templates原理初探索

[写在前面的话]这篇文章先发布在https://my.oschina.net/chenx124208739/blog/876964里了,但是公司的网络登录开源中国还是很困难,于是只能食言返回51cto(但是51cto把长代码转化代码格式的处理上真的很烂),就这样吧,在这里继续记录我的工作点滴! 运维的工作时间总是很零散的,首先要应付服务器的告警,然后还要伺候各路开发,再加上一些扩容.续费.开会这样的杂事,最后在烧香不出意外情况的前提下才能有一点时间是属于你自己拓展业务.从清明节结束一路忙到现在,