Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: All
May 19, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Test templates thoroughly

To write a test routine for a template class or function, you have to choose one concrete type for every formal type of the template and run all tests on this instantiation of the template. Consider this buggy template function:

     template <class T>
     double max (T t1, T t2)
         return t1>t2 ? t1 : t2;

Clearly, the return value should be a T, not a double. Errors like that appear surprisingly frequently, because many templates were originally designed as non-template classes/functions. If your test routine only tests the case that T is double, this error does not reveal itself!

The first conclusion is obvious: A sound test of a template checks several instantiations, and in that, every formal type parameter is to be instantiated by more than one type.

The second conclusion is less obvious: Every formal type parameter should also be instantiated at least once by a self-defined type. Why? Even if you test the above function max using various built-in types such as double, int, and char, your test routine might not encounter an error, because all of these types are silently converted to double!

Karsten Weihe
Comment and Contribute






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



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