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

时间:2017-10-28 09:17:24

标签: c++11 stl unordered-set template-classes

我无法理解模板类的用途是什么? 我是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

1 个答案:

答案 0 :(得分:0)

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

#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;
}