Templates

There are function and class templates.

Basic idea is to save code lines by keeping a type specifier generic in your function/class definition, till you need an instance of your function/class, where you then specify the type directly or indirectly.

Template-Hello-World example with a function and a class template

#include <stdio.h>
#include <tchar.h>
#include <iostream>
 
using namespace std;
 
 
 
// Here is a function template:
template <typename T>
T someFunc_WhatIsLarger(T x, T y)
{
  T value;
 
  if (x < y)
    value = y;
  else
    value = x;
  //
  return value;
}
 
 
// Here is a class template:
template <class T>
class mypair {
 
  public:
 
    // Some class data
    T values [2];
 
    // Class constructor
    mypair (T first, T second)
    {
      values[0]=first; values[1]=second;
    }
 
};
 
 
 
 
int _tmain(int argc, _TCHAR* argv[])
{
    // 1. Function template tests
 
    // Generate function instance from template for int values
    // Indirect definition of type to use for function template
    cout << someFunc_WhatIsLarger(1,5) << endl;
 
    // Generate function instance from template for float values
    // Indirect definition of type to use for function template
    cout << someFunc_WhatIsLarger(1.0, 5.0) << endl;
 
    // Won't compile!
    // error C2782: 'const _Ty &std::max(const _Ty &,const _Ty &)' : template parameter '_Ty' is ambiguous
    //std::cout << max(1, 5.0) << std::endl;
 
    // Will compile!
    // Direct definition of type to use for function template
    std::cout << max<float>(1, 5.0) << endl;
 
 
 
    // 2. Class template tests
 
    // Create an object instance of mypair for type 'int'
    mypair<int> myobject1 (1, 5);
 
    // Create an object instance of mypair for type 'float'
    mypair<float> myobject2 (1.0, 5.0);
 
 
    cout << someFunc_WhatIsLarger( myobject1.values[0], myobject1.values[1] ) << endl;
 
    cout << someFunc_WhatIsLarger( myobject2.values[0], myobject2.values[1] ) << endl;
 
    // Won't compile!
    // error C2782: 'T someFunc_WhatIsLarger(T,T)' : template parameter 'T' is ambiguous
    //cout << someFunc_WhatIsLarger( myobject1.values[0], myobject2.values[0] ) << endl;
 
 
    std::cin.get(); //wait for keypress    
}

error C2955: use of class template requires template argument list

see this article 'How to define a template class in a .h file and implement it in a .cpp file'

 
public/templates.txt · Last modified: 2012/10/15 09:53 (external edit) · []
Recent changes RSS feed Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki