#include <iostream>
#include <typeinfo>
using namespace std;
// template function
template <typename T> T cube(T value)
{
cout << "Cubing a " << typeid(T).name() << " (template): " << value << endl;
return value * value * value;
}
// regular function declaration
int cube(int value);
// explicit specialization cube<int> declaration
template <> int cube(int value);
Cube.cpp: Implementations and explicit instantiations
#include "cube.h" // templates, declarations only
// regular function (non-template)
int cube(int value)
{
cout << "Cubing an int (regular): " << value << endl;
return value * value * value;
}
// explicit specialization cube<int>
template <> int cube(int value)
{
cout << "Cubing an int (specialization): " << value << endl;
return value * value * value;
}
// explicit instantiations
template double cube(double); // Deduces cube<double>
template float cube(float); // Deduces cube<float>
template char cube(char); // Deduces cube<char>
FileCube1.cpp: Using template functions
#include <iostream>
using namespace std;
#include "cube.h"
void UseCube1(void)
{
cout << "In FileCube1: UseCube1 ***********************************************\n";
// MSVC 6.0 GNU/BOR/7.1
cout << cube(5) << endl; // regular regular
cout << cube<double>(10L) << endl; // template template
cout << cube(2.5F) << endl; // template template
cout << cube<int>(2.5) << endl; // regular special (warning possible loss of data)
cout << cube<char>(5) << endl; // template template
cout << cube('A') << endl; // template template
cout << cube<int>(25) << endl; // regular special
}
FileCube2.cpp: Using template functions
#include <iostream>
using namespace std;
#include "cube.h"
void UseCube2(void)
{
cout << "In FileCube2: UseCube2 ***********************************************\n";
// MSVC 6.0 GNU/BOR/7.1
cout << cube(5) << endl; // regular regular
cout << cube<double>(10L) << endl; // template template
cout << cube(2.5F) << endl; // template template
cout << cube<int>(2.5) << endl; // regular special (warning possible loss of data)
cout << cube<char>(5) << endl; // template template
cout << cube('A') << endl; // template template
cout << cube<int>(25) << endl; // regular special
}
CubeMain.cpp: Using template functions
#include <iostream>
using namespace std;
#include "cube.h"
void UseCube1(void);
void UseCube2(void);
int main(void)
{
UseCube1();
UseCube2();
cout << "In main ***********************************************\n";
// MSVC 6.0 GNU/BOR/7.1
cout << cube(5) << endl; // regular regular
cout << cube<double>(10L) << endl; // template template
cout << cube(2.5F) << endl; // template template
cout << cube<int>(2.5) << endl; // regular special (warning possible loss of data)
cout << cube<char>(5) << endl; // template template
cout << cube('A') << endl; // template template
cout << cube<int>(25) << endl; // regular special
return 0;
}