c++中的template类模板与函数模板

C++ 提高编程 Python微信订餐小程序课程视频 https://edu.csdn.net/course/detail/36074 Python实战量化交易理财系统 https://edu.csdn.net/course/detail/35475 目录* C++ 提高编程 + 一、 模板 - 1、 概念 - 2、 函数模板 * 2.1 函数模板语法 * 2.2 注意事项 * 2.3 普通函数和函数模板的区别 * 2.4 普通函数和函数模板的调用规则 * 2.5 模板的局限性 - 3、 类模板 * 3.1 类模板语法 * 阅读详情

c++中的template类是一种很高端的用法。它是一种模板,有类模板、函数模板等。

一、类模板

想实现swap函数,但又不会实现对任意类的交换,怎么办?

template大法!

template <typename T>
void myswap(T &__a,T&__b){
	T __c;
	__c=__a;
	__a=__b;
	__b=__c;
}

解释一下:

1.typename

typename是用来规定后面的T是类型名,而非变量名。如果是两个double类型交换,那么T就为double,如果是两个结构体交换,那么T就是结构体名。

2.取地址符 ‘&’

对于要交换的两个数__a和__b,如果不加’&’,就只是在myswap函数里面交换,而对数本身没有影响。’&'实质上是一种指针,指向要交换的两个数。

例:

scanf("%d %d",&a,&b);

如果在较为复杂的程序里面不加’&’,就会编译错误或结果错误。

3. ___a与___b

为什么要用__a和__b呢?

在写头文件的过程中,如果不这样写,有时就会导致编译错误,即:头文件中的变量与程序之间的变量重复。

二、模板函数

对于以下程序片段:

template <class S>
class A{
	private:
		S __d;
		int __e;
	public:
		S plus(S __a,S __b);
		A();
};

你既可以将它写成一个头文件,也可以直接写在程序中。

class与typename相似。

引用时需这样:\text{引用时需这样:}引用时需这样:

#include<bits/stdc++.h>
#include "templatetry.h"
using namespace std;
template <class S> A<S>::A() {}
template <class S> S A<S>::plus(S __a,S __b) {
	return __a+__b;
}
int a,b;
int main(){
	cin>>a>>b;
	myswap(a,b);
	A<int> c;
	cout<<a<<' '<<b<<endl;
	cout<<c.plus(a,b);
	return 0;
}
模板 模板定义:模板就是实现代码重用机制的一种工具,它可以实现类型参数化,即把类型定义为参数,从而实现了真正的代码可重用性。模版可以分为两类,一个是函数模版,另外一个是类模版。 函数模板的一般形式如下: Template 或者也可以用typename T> 返回类型函数名(形参表) {//函数定义体 } 说明: template是一个声明模板的关键字,表示声明一个模板关键字class不能省略, 阅读详情

相关推荐

[C++高级部分] 泛型编程和STL技术 黑马课程学习笔记

C++的另一种编程思想称为泛型编程,主要利用的技术就是模板;C++提供两种模板机制:函数模板和类模板建立一个通用函数,其函数返回值类型与形参类型不具体制定,而是用一个虚拟的类型来代表 使用函数模板:①自动类型推导 直接像调用函数一样,传入实参即可,编译器自动推导出实参的类型 ②显示指定类型 函数名传入实参值基本语法和函数模板差不多,无非就是模板参数列表中多加了几个模板类型 调用时:Person p1 (“孙悟空”, 999);...

a123456_9的博客 293

深度探索c++对象模型之template中的名称决议方式

我们应该能够区分以下两种意义:一个是c++ standard标准中的“scope of the template definition”【模板定义域】,另一个是c++ standard标准中的“scope of the template instantiation”【模板具现域】。第一种情况举例说明:// scope of the template definition【模板定义域】 exter

wenpinglaoyao的专栏 880

侯捷C++程序设计及对象模型之---(6)namespace经验谈 & (7)类模板 & (8)函数模板& (9)成员模板

function-like class

qq_41593516的博客 233

C++类模板详解

有时,有两个或多个类,其功能是相同的,仅仅是数据类型不同,如下面语句声明了一个类: class Compare_int{public : Compare(int a,int b) { x=a; y=b; } int max( ) { return (x>y)?x:y; } int min( ) { return (x

sfe1012 Na~喊 -- 心系一处 睥睨群雄 Blog 2548

比亚迪开放平台接口实战:车身状态监测与智能车联应用开发

本文详细介绍了如何利用比亚迪开放平台的车身状态接口进行智能车联应用开发。通过核心类BYDAutoBodyworkDevice,开发者可以安全获取车辆VIN、车门车窗状态、蓄电池电压、方向盘转角等实时数据,并利用监听器实现状态实时响应。文章提供了从SDK集成、接口调用到典型应用场景(如远程车况检查、车队管理)的完整实战指南,助力开发者快速构建基于比亚迪车辆数据的创新应用。

weixin_29176179的博客 714

PHP 对接建行生活订单推送接口

php对接建行订单推送

qq_43647026的博客 559

C++模板template用法总结

引言 模板(Template)指C++程序设计设计语言中采用类型作为参数的程序设计,支持通用程序设计。C++ 的标准库提供许多有用的函数大多结合了模板的观念,如STL以及IOStream。 函数模板 在c++入门中,很多人会接触swap(int&, int&)这样的函数类似代码如下: void swap(int&a , int& b) { int temp = a; a = b; b = temp; } 但是如果是要支持long,str.

nihao_2014的博客 1628

VMware Workstation Pro 16 安装 Ubuntu 20.04

VMware Workstation Pro 16 安装 ubuntu 20.04目录环境VMware Workstation下载Ubuntu 20.04下载安装过程 目录 环境 Windows 10 Workstation 16 Pro for Windows Ubuntu 20.04 LTS 64位 desktop版本 VMware Workstation下载 链接: https://www.vmware.com/products/workstation-pro/workstation-pro-eval

qq_45642410的博客 1万+

C++类模板之双重模板参数(Template Template Parameters)

一个 模板参数 本身也可以是个 类模板。我们还是以Stack<T>为例子 为了使用其它类型的元素容器,stack class 使用者必须两次指定元素类型:一次是元素类型本身, 另一次是容器类型 Stack<int,std::vector<int> > vStack; // int stack,以 vector为容器 如果使用 template tem...

sinat_31608641的博客 5085

晶体管-二极管三极管MOS管选型参数总结

二极管三极管和MOS管,是电路中常用的控制电流电压的基本电子元器件。电路世界中晶体管的选型,需要考虑的参数多种多样,这些参数的选择会直接影响到电路的性能、稳定性、成本等多个方面。本文对二极管三极管和MOS管的选型参数进行详细介绍并总结。

fydar的博客 884

【Inpho精品教程】Inpho简介、安装教程(附Inpho8安装包下载)

本文介绍Trimble旗下Inpho UASMaster航空摄影测量软件,涵盖其核心功能模块(如Match-AT、OrthoMaster、Summit Evolution等)及安装教程。文章详细说明了从安装到汉化破解的全过程,并提供Inpho 8.0.1安装包下载链接与提取码,适用于无人机摄影测量专业用户。

智慧空间实验室 1万+

C++双重模板

Template Template Paraments(双重模板参数)模板参数本身也可以是一个类模板,例如实现一个Stack class。为了使用其他类型的元素容器,使用者必须两次指定元素类型:一次是元素类型本身,另一次是容器类型:Stack<int,std::vector> vStack; //int stack,以vector为容器如果使用template template parameter

GuFanYuan的专栏 2462

泛微OA与泛微OA之间打通实现统一待办配置

问题:学校OA与集团OA均为泛微Ecology8.0 ,由于流程审批互通的需要,要将两套OA系统打通,实现跨系统的流程流转。

symstandsun的博客 2269

Cpp-Templates-2ed完全指南:从C++11到C++20的终极模板编程教程

C++模板是C++11至C++20标准中最复杂也最强大的特性之一,是构建高性能基础设施库不可或缺的技术。本教程将带你从基础到进阶,全面掌握现代C++模板编程的核心技术与最佳实践。 ## 为什么模板是C++开发者的必备技能 🚀 模板作为C++的元编程基础,允许开发者编写与类型无关的通用代码,在保持类型安全的同时实现代码复用。无论是STL标准库、Boost库,还是现代C++基础设施,模板技术都扮

gitblog_00195的博客 683

基于Termux的Android平台OpenClaw部署:移动端AI助理实现

本文介绍了在Android设备上通过Termux部署OpenClaw AI助理的方案。Android设备的便携性、Termux提供的完整Linux环境以及多样化的硬件配置使其成为理想的部署平台。文章详细分析了不同级别Android设备的硬件规格(从入门级到旗舰级),并提供了最低/推荐配置要求。部署步骤包括Termux安装初始化、Python环境配置以及性能优化建议。该方案充分利用Android设备的传感器和电池供电优势,为移动办公、学习等场景提供了低成本、高便携性的AI助理解决方案。

博客 3010

DC/DC开关电源学习笔记(十三)Buck-Boost升降压电路工作原理

Buck-Boost电路是一种能够实现输出电压高于或低于输入电压的DC-DC变换器,且输出电压极性与输入电压相反。它结合了Buck(降压)和Boost(升压)两种拓扑的特点,广泛应用于需要灵活电压调整的场合,如电池供电设备、LED驱动和工业控制系统。本文将从电路结构、工作原理、关键公式推导及实际应用等方面进行详细分析。

小幽余生不加糖 3503

十六、Template(模板)

Template重用的是源代码,而不是像继承和组合那样重用对象代码。Template 通过使用类型作为参数,直接支持泛型编程(写一次代码,用多种类型)。Template(模板) 包括类模板和函数模板。从模板生成类或函数的过程被称为模板实例化。模板实例化fill:#333;color:#333;color:#333;fill:none;实例化Instantiation实例化Instantiation实例化Instantiation模板Templates。

xjsj62728的博客 1234

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

如何使用函数模板和类模板?模板的优点是什么?

例如,你可以编写一个通用的排序函数模板,它可以对各种类型的数组进行排序,而无需为每种数据类型单独编写一个排序函数。例如,你可以使用模板来实现不同数据结构的容器类,如链表、栈和队列,这些容器可以存储不同类型的数据,并且可以根据需要进行定制。此外,模板还可以减少函数调用的开销,因为模板函数可以进行内联展开,避免了函数调用的额外开销。在 C++中,函数模板和类模板是强大的工具,可以实现代码的通用性和可重用性。在这个例子中,MyClass是一个类模板,T是模板参数,表示类中的数据成员可以是任何类型。

SUN_Gyq的博客 617

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

极简c++(9)函数模板与类模板

后续需要可以自己查看补充。

weixin_45636780的博客 104

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

C/C++: 关键字template的用法

template。

weixin_42849849的博客 853

C++的函数模板和类模板

就是允许编写依次函数定义然后用于不同数据类型,而不用每种类型单独编写函数。: 与函数模板类似,就是创建一个通用类,可以实例化各种数据类型。( 可以类比C语言中的宏定义来对比认知 )使用 template 关键字进行模板定义。

qq_50900759的博客 272

Effective C++ 条款44 将与参数无关的代码抽离template

1、必须认识在C++中使用template时,有哪些类型的参数。形如template&lt;typename T, std::size_t n&gt;,可知:(1)type template parameters(类型模板参数);(2)non-type template parameters(非类型模板参数)。 2、必须认识template参数可作用的对象有哪些?(1)作用于类class时,称为...

cnkicq的专栏 281

C++:模板

●模板的概念 ●在C++标准库中,几乎所有的代码都是模板代码。 ●模板是对具有相同特性的函数或类的再抽象,模板是一种参数化的多态性工具。 ●所谓参数化多态性,是指将程序所处理的对象的类型参数化,使一段程序代码可以用于处理多种不同类型的对象。 ●采用模板编程,可以为各种逻辑功能相同而数据类型不同的程序提供一种代码共享的机制。 ●函数模板 ●模板函数 ●类模板与模板类 ●类模板的友元 ●STL标准库的相关内容(迭代器、算法、容器等) ...

qq_53826699的博客 396

C++进阶学习:模板

C++中的模板属于泛型编程工具 允许编写与数据类型无关的通用代码编译器会根据调用时的具体类型自动生成对应的代码C++中的一种编程思维被称为范式编程 主要利用的技术就是模板C+=提供两种模板机制 函数模板和类模板。

Miki Makimura 的博客 1094

C++学习 -- template

模板template主要用于解决类型的参数化,在调用处指定一个类型像参数一样传到定义处就可以使定义处特定位置上的类型使用指定的类型,这样可以避免因为只是参数类型不同而功能相同的函数重复定义,做到统一性。下面的文章从相同功能参数类型不同的重载函数引出模板的必要性,再到模板的分类(函数模板、类模板)和定义、使用循序渐进,最后到非类型模板参数。         http://blog.csdn.n

大风的专栏 245

static ,auto ,template的一个小例子

#include &lt;iostream&gt; class Foo { public: static int get(void) { return 0; } }; class Bar { public: static const char* get(void) { return "0"; } }; template &lt;class A&gt; void func(vo...

konglingshneg的博客 429
上一篇: 解方程头文件
下一篇: 洛谷P1953 易语言
return_dr
博客等级 码龄5年 216粉丝 105原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值