2017-10-28 43 views
-1

我不明白什么是模板类用于? 我是新来的C++。我可以得到详细的解释。模板类在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 
+2

[阅读了良好的初学者两本书](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 –

+0

你能建议我一些他做的 –

+0

。这是一个链接。 – Yunnosch

回答

0

C++模板类/功能基本上是一个通用类/功能即你只需要一次定义的类或功能并且可以使用此定义为不同的数据类型(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; 
}