【cmu15445c++入门】(4)c++中的模板方法

一、template模板方法

模板方法是c++的一个特性,可以让你的代码在不指定数据类型的情况下,运行不同的数据类型。

你可以创建模板方法和模板类,本文讨论模板方法。

二、代码

cpp 复制代码
// Includes std::cout (printing) for demo purposes.
#include <iostream>

// Templates are a language feature in C++ that allow you to write code that
// can work with multiple data types, without actually specifying those types.
// In C++, you can create both templated functions and templated classes. We'll
// talk about templated functions in this file.

//模板方法是c++的一个特性,可以让你的代码在不指定数据类型的情况下,运行不同的数据类型。
//你可以创建模板方法和模板类,这个文件讨论模板方法。

// Here is a basic templated function that adds two numbers.
// Syntax note: You will see code with both template<class T> and
// template<typename T>. Although these statements are equivalent, there are
// differences between the class and typename keywords. This blog article covers
// this difference, but you won't need to know this for the class:
// https://mariusbancila.ro/blog/2021/03/15/typename-or-class/

//模板方法,计算两个数字的和
template <typename T> 
T add(T a, T b) { return a + b; }

// It is possible to pass multiple type names via templates into functions.
// This function will print both of these values out.
// 传入多个类型的模板方法
template<typename T, typename U>
void print_two_values(T a, U b) {
  std::cout << a << " and " << b << std::endl;
}
template<typename T, typename U, typename V>
void print_three_values(T a, U b,V c) {
  std::cout << a << " and " << b << " and " << c <<std::endl;
}
template<typename T, typename U, typename V,typename W>
void print_four_values(T a, U b,V c,W d) {
  std::cout << a << " and " << b << " and " << d <<std::endl;
}
template<typename T, typename U, typename V,typename W,typename X>
void print_five_values(T a, U b,V c,W d,X e) {
  std::cout << a << " and " << b << " and " << e <<std::endl;
}

// It is also possible to create specialized templated functions, that do
// different things for different types. Take the following contrived example,
// which prints the type if its a float type, but just prints hello world for
// all other types.
// 也能根据不通的类型,制定不同的模板方法。
template <typename T> 
void print_msg() { std::cout << "Hello world!\n"; }

// Specialized templated function, specialized on the float type.
// 对float类型单独定制
template <> 
void print_msg<float>() {
  std::cout << "print_msg called with float type!\n";
}

// Lastly, template parameters do not have to be classes. Take this basic (yet
// very contrived) function that takes in a bool as a template parameter and
// does different things to the argument depending on the boolean argument.
// 这个做法不推荐
template <bool T> int add3(int a) {
  if (T) {
    return a + 3;
  }

  return a;
}

int main() {
  // First, let's see the add function called on both ints and floats.
  std::cout << "Printing add<int>(3, 5): " << add<int>(3, 5) << std::endl;
  std::cout << "Printing add<float>(2.8, 3.7): " << add<float>(2.8, 3.7)
            << std::endl;

  // It is also possible for a templated function to interpret the type of its
  // arguments, although if you're a beginner in modern C++, it's preferred you
  // don't do this because then you might not be sure of the types being passed
  // into your functions.
  // 也可以不指定类型,但初学者不建议
  std::cout << "Printing add(3, 5): " << add(3, 5) << std::endl;

  // Second, let's see the print_two_values function being called with two
  // different types.
  std::cout << "Printing print_two_values<int, float>(3, 3.2): ";
  print_two_values<int, float>(3, 3.2);

  print_three_values<int, float, double>(3, 3.2,2.14);
  print_four_values<int, float, double,float>(3, 3.2,2.14,2.12);
  print_five_values<int, float, double,float,int>(3, 3.2,2.14,2.12,6);
  // Let's see what happens when we called print_msg with and without the float
  // type being passed in. As expected, the first call to print_msg prints out
  // the general output, while the second one, with the float argument,
  // recognizes its type parameter and calls the specialized function.
  std::cout << "Calling print_msg<int>(): ";
  print_msg<int>();
  std::cout << "Calling print_msg<float>(): ";
  print_msg<float>();

  // add3 has the specified behavior for both a true and false templated
  // argument, as we can see here.
  std::cout << "Printing add3<true>(3): " << add3<true>(3) << std::endl;
  std::cout << "Printing add3<false>(3): " << add3<false>(3) << std::endl;

  // Lastly, it's important to note that most of these are contrived examples,
  // and it is possible to code some of these functions (e.g. passing a boolean
  // as an argument instead of a templated argument) without using templates.
  // However, in the class, you'll be seeing code similar to this in the
  // codebase, so it's good to understand templated functions in these contexts!
  // 最后,需要注意的是,以上大多数都是人为的示例,并且有的是可以不使用模板,而是对其中一些函数进行编码
  //(例如,将布尔值作为参数而不是模板化参数传递)。但是,海量的代码库中很可能也看到与此类似的代码,因此最好在这些上下文中理解模板化函数!
  return 0;
}

运行结果

相关推荐
爱吃喵的鲤鱼1 小时前
linux进程的状态之环境变量
linux·运维·服务器·开发语言·c++
7年老菜鸡1 小时前
策略模式(C++)三分钟读懂
c++·qt·策略模式
Ni-Guvara2 小时前
函数对象笔记
c++·算法
似霰2 小时前
安卓智能指针sp、wp、RefBase浅析
android·c++·binder
芊寻(嵌入式)2 小时前
C转C++学习笔记--基础知识摘录总结
开发语言·c++·笔记·学习
獨枭2 小时前
C++ 项目中使用 .dll 和 .def 文件的操作指南
c++
霁月风2 小时前
设计模式——观察者模式
c++·观察者模式·设计模式
橘色的喵2 小时前
C++编程:避免因编译优化引发的多线程死锁问题
c++·多线程·memory·死锁·内存屏障·内存栅栏·memory barrier
何曾参静谧2 小时前
「C/C++」C/C++ 之 变量作用域详解
c语言·开发语言·c++
AI街潜水的八角3 小时前
基于C++的决策树C4.5机器学习算法(不调包)
c++·算法·决策树·机器学习