dcsimg
LinkedIn
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


advertisement
 

Use an Asymmetric Assignment Operator to Assign Containers of Different Types

Learn how to simulate the implicit conversion of built-in datatypes with different specializations of the same template by adding an asymmetric assignment operator to the class template.


advertisement
++ implicitly converts the operands' types in expressions that involve different datatypes. Here's a few examples:

int n=5;
double d=n; //5 implicitly converted to 5.0
if (n==d) //same here
Many programmers don't even know that these implicit conversions take place because they are so trivial and intuitive. However, when templates are involved, it's a different story. Consider the following:

Array<int> ai;
Array<double> ad;
ai.push_back(5);
ad=ai;//compilation error
The assignment of Array<int> to Array<double> fails because there is no standard conversion between these two independent types.


How do you simulate the implicit conversion of built-in datatypes with different specializations of the same template?


Add an asymmetric assignment operator to the class template.

Notes on Terminology: The terms "template member" and "member template" sound like synonyms. They aren't. A template member is a member of a class template. For example:

template <classt T> class Array
{
 T * p; // p is a template member
 void func(T &) const; // so is func
};
By contrast, a member template is a template declared within a class or class template. This 10-Minute Solution uses a member template to overcome the lack of implicit conversions between different specializations of the same class template.



Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date