You can restrict the type of template arguments for a template class by using the
Forward template declaration.
Suppose you have a template class and you want to instantiate it only for types int and double:
//test.h
template<class type>
class test
{
public:
test(type x);
type getValue();
type m_value;
};
//test.cpp
#include "test.h"
template test<int>;//Forward template declaration
template test<double>;//Forward template declaration
template<class type >
test<type>::test(type t):m_value(t)
{
}
template<class type>
type test< type >:: getValue ()
{
return m_value;
}
#include "test.h"
int main()
{
test<int> t1(123); //This will compile
test<double> t2(6.5); //This will compile
cout << t1. getValue () << endl;
cout << t2. getValue () << endl;
// test<const char*> t3(sau); //This will not compile
return 0;
}