c++中模板class的目的是什么

what is the purpose of template class in c++

我不明白模板 class 有什么用? 我是 C++ 的新手。能详细解释一下吗

// constructing unordered_sets
#include <iostream>
#include <string>
#include <unordered_set>

template<class T>
T cmerge (T a, T b) { T t(a); t.insert(b.begin(),b.end()); return t; }

std::unordered_set<std::string> second ( {"red","green","blue"} );    // init list
std::unordered_set<std::string> third ( {"orange","pink","yellow"} ); // init list
std::unordered_set<std::string> fourth ( second );
std::unordered_set<std::string> fifth ( cmerge(third,fourth) );       // move

C++ 模板 class/function 基本上是一个通用的 class/function 即,您只需定义一次 class 或函数,您就可以将此定义用于不同的数据类型(int,字符,浮动等)。 例如:-

#include <iostream>
using namespace std;

// One function works for all data types.  This would work
// even for user defined types if operator '>' is overloaded
template <typename T>
T myMax(T x, T y)
{
   return (x > y)? x: y;
}

int main()
{
  cout << myMax<int>(3, 7) << endl;  // Call myMax for int
  cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double
  cout << myMax<char>('g', 'e') << endl;   // call myMax for char

  return 0;
}