devxlogo

Restrict the Types of Template Argument for a Template Class

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.htemplateclass test{public:     test(type x);     type getValue();     type m_value;};//test.cpp#include "test.h"template test;//Forward template declarationtemplate test;//Forward template declarationtemplatetest::test(type t):m_value(t){}templatetype test< type >:: getValue (){     return m_value;}#include "test.h"int main(){     test t1(123);		//This will compile     test t2(6.5);	//This will compile          cout << t1. getValue () << endl;     cout << t2. getValue () << endl;         // test t3(sau);	//This will not compile     return 0;}

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Five Early Architecture Decisions That Quietly Get Expensive

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.