zoukankan      html  css  js  c++  java
  • C++模板

    C++模板主要解决类型多态,对于定义和使用的话,其实也是很简单的理解

    简单写了两个示例


    一、函数模板

    假如我需要计算两个值相加,但可能会传入float或者int等不同类型的值,

    以往我们回考虑到各种情况,可能会写几个重载函数来解决这个问题,

    现在可以使用模板函数,正好也解决写一些多余的代码啊,具体如下

    #include "stdafx.h"
    #include <iostream>
    
    /*
    template为模板声明,
    <>里为模板参数列表,不能为空,可以多个
    如果需要在其他地方定义或者需要再函数类再定义一个类型,编译器不是能识别的,是需要用typename再次声明
    */
    template<typename T> //这里的typename也可以用class代替,为了与类模板混淆,才有了typename,其实都一样
    T AddNum(T Num01, T Num02)
    {
    	return Num01 + Num02;
    }
    
    int main()
    {
    	std::cout << "int add:@@ " << AddNum(10, 23) << std::endl;
    	std::cout << "float add:@@ " << AddNum(16.0f, 3.0f) << std::endl;
    	while (true)
    	{}
        return 0;
    }

    二、类模板

    类模板如果说到vector或者list,其实就更好理解了,基本上都属于常用的东西

    我这里就简单输出了一串字符

    #include "stdafx.h"
    #include <iostream>
    
    /*
    template为模板声明
    class与typename一样,
    其他都一样,需要定义为不确定类型,用typename/class声明一下
    在类体外实现函数或初始化变量,且他们都带模板变量的话,需要在使用的地方再次声明一遍
    */
    template <class T>
    class PrintT
    {
    public:
    	T Value;
    };
    
    int main()
    {
    	PrintT<char*>* pt = new PrintT<char*>();
    	pt->Value = "test print";
    
    	std::cout << "char print:@@ "<<(pt->Value)<<std::endl;
    	while (true)
    	{}
        return 0;
    }


  • 相关阅读:
    UVA 10617 Again Palindrome
    UVA 10154 Weights and Measures
    UVA 10201 Adventures in Moving Part IV
    UVA 10313 Pay the Price
    UVA 10271 Chopsticks
    Restore DB後設置指引 for maximo
    每行SQL語句加go換行
    种服务器角色所拥有的权限
    Framework X support IPV6?
    模擬DeadLock
  • 原文地址:https://www.cnblogs.com/liang123/p/6325859.html
Copyright © 2011-2022 走看看