Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Dec 18, 2000

Covariant Template Parameters


Suppose you need to define a function that takes a vector object and performs certain operations on it. The function has to be generic, that is, it should handle all instances of std::vector in the same way. The best way to achieve such generic behavior is by defining the function as a template whose parameter covaries with the vector's parameter. In the following example, the insert_one() function template inserts a default-initialized element to a vector, regardless of the element's type:
 
#include <vector>
using namespace std;

// the parameter T of insert_one() covaries with vector's T
template <class T> void insert_one(vector<T> &v)
{
 T t=T(); // ensure built-in types are default-initialized
 v.push_back(t);
}
int main()
{
 vector <int> vi;
 vector <char> vc;
 insert_one(vi);
 insert_one(vc);
}
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap