Generic Function Template

posted Nov 30, 2014, 9:10 PM by Javad Taghia   [ updated Nov 30, 2014, 9:21 PM ]


YouTube Video



In C++'s generic programming feature known as "templates", typename can be used for introducing a template parameter:[1][2]

// Define a generic function that returns the greater of its two arguments
template <typename T>
const T& max(const T& x, const T& y)
{
  if (y < x)
    return x;
  return y;
}

An alternative and semantically equivalent keyword in this scenario is "class":

// Define a generic function that returns the greater of its two arguments
template <class T>
const T& max(const T& x, const T& y)
{
  if (y < x)
    return x;
  return y;
}
Example:
#include <algorithm>
#include <vector>
#include <boost/numeric/ublas/storage.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

namespace ublas = boost::numeric::ublas;

template <typename T, typename F=ublas::row_major>
ublas::matrix<T, F> makeMatrix(std::size_t m, std::size_t n, const std::vector<T> & v)
{
    if(m*n!=v.size()) {
        ; // Handle this case
    }
    ublas::unbounded_array<T> storage(m*n);
    std::copy(v.begin(), v.end(), storage.begin());
    return ublas::matrix<T>(m, n, storage);
}

int main () {;
    std::vector<double> vec {1, 2, 3, 4, 5, 6};
    ublas::matrix<double> mm = makeMatrix(3,2,vec);
    std::cout << mm << std::endl;
}

Comments