CPP/FunctionTemplateSpecialization
From ProgrammingExamples
< CPP
FunctionTemplateSpecialization.cpp
#include <iostream> #include <vector> #include "Point.h" int main(int argc, char* argv[]) { std::vector<unsigned int> A; for(unsigned int i = 0; i < 3; i++) { A.push_back(i * 1.3); } Output(A); std::vector<double> B; for(unsigned int i = 0; i < 3; i++) { B.push_back(i * 1.3); } Output(B); std::vector<int> C; for(unsigned int i = 0; i < 3; i++) { C.push_back(i * 1.3); } Output(C); return 0; }
Point.cpp
#include "Point.h" #include <iostream> #include <vector> template <> void Output<double>(std::vector<double> &V) { std::cout << std::endl << "double" << std::endl << "----------" << std::endl; for(unsigned int i = 0; i < V.size(); i++) { std::cout << V[i] << std::endl; } } template <> void Output<unsigned int>(std::vector<unsigned int> &V) { std::cout << std::endl << "unsigned int" << std::endl << "----------" << std::endl; for(unsigned int i = 0; i < V.size(); i++) { std::cout << V[i] << std::endl; } }
Point.h
#ifndef POINT_H #define POINT_H #include <iostream> #include <vector> //MUST put the definition here template <typename T> void Output(std::vector<T> &V) { std::cout << std::endl << "other" << std::endl << "-------" << std::endl; for(unsigned int i = 0; i < V.size(); i++) { std::cout << V[i] << std::endl; } } #endif