#include <iostream>
using namespace std;
template <class T> inline T Max(T a, T b) { return a > b ? a : b; }
int main() { int a = 1, b = 2;
cout << Max(a, b) << endl; cout << Max(1.0, 2.0) << endl; cout << Max("hello", "world") << endl;
return 0; }
|
2.类模板
#include <iostream>
using namespace std;
template <class T> class A { private: T a; public: A(T x) { a = x; } T get() { return a; } };
int main() { A<double> a(10);
cout << a.get() << endl;
return 0; }
|
3.模板特殊化:当你在使用一个模板,而又想对某一个特殊的类型做不同的实现时,就需要一个特殊化的模板声明。
// template specialization #include <iostream> using namespace std;
// class template: template <class T> class specTemplate { T m_var; public: specTemplate (T inData) { m_var = inData; } T increase () { return ++m_var; } };
// class template specialization: template <> class specTemplate <char> { char m_var; public: specTemplate (char arg) { m_var = arg; } char upperCase () { if ((m_var >= 'a') && (m_var <= 'z')) m_var += 'A'-'a'; return m_var; } };
int main () { specTemplate<int> myint (7); specTemplate<char> mychar ('j');
cout << myint.increase() << endl; cout << mychar.upperCase() << endl; return 0; }
|
4.模板默认值:
template <class T = char, int N = 10> class Test {..};
|
1)模板的类型也可有默认值;
2)模板的类型也可以是regular type,并非一定是以class或typename修饰的类型;
分享到:
相关推荐
C++ template 中文版 候捷。 很好的学习C++ template 的资料。
C++Template just down load it !
C++ Template C++ Template The complete Guide-examples
c++template 侯捷简体版本,转换的效果还不错
example of c++ template
收录目前网上所有 C++ Template版本, 中文, 英文, 简体繁体等.
C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond,《C++模板元编程》英文版。C++ In-Depth系列丛书之一,C++程序员必备。
C++模版编程,C++Template书籍 + 代码资源,分享给大家一起学习学习
这是C++ Template Metaprogramming原书附带的例子代码,可以方便各位进行研习,请首先编译开篇的第一个例子,以测试你手头的编译器对模板的支持程度。 另,有的亲反映上载的书无法打开,可能是Windows7进行了权限...
Addison Wesley - C++ Template Metaprogramming Concepts Tools And Techniques From Boost And Beyond
C++元编程参考 英文版计算机编程经典教材 适合学习软件构造的人参考
C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond
侯捷等人翻译的 简体中文版的 《C++ template 全览》 的 第一篇的前5节内容,后面内容还没整理好。
C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond By David Abrahams, Aleksey Gurtovoy Publisher : Addison Wesley Professional Pub Date : December...
C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond,《C++模板元编程》英文版。C++ In-Depth系列丛书之一,C++程序员必备。
c++ templatec++ templatec++ template
一本很薄的讲模板的书
《C++ Template》第二版,2017年9月16日出版 Templates are among the most powerful features of C++, but they remain misunderstood and underutilized, even as the C++ language and development community ...