Covariant Template Parameters

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 using namespace std;// the parameter T of insert_one() covaries with vector's Ttemplate  void insert_one(vector &v){ T t=T(); // ensure built-in types are default-initialized v.push_back(t);}int main(){ vector  vi; vector  vc; insert_one(vi); insert_one(vc);}



Share the Post: