Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit-testing C++ templates

I've used function and class templates in implementation of my libraries. So far I've just instantiated a template in the library unit-tests (CppUnit), and then proceeded to test it almost like any other normal class or function.

Recently I've been planning to add some templates also to the library APIs. Good interface is of course the most important thing, template or not. With well designed and implemented templates you can, if not totally prevent, at least make it more difficult for the user to shoot himself in the foot. Any way I feel that unit-testing public templates need to be a bit more rigorous, compared to purely internal templates.

So, how have you unit-tested your C++ templates? Have you come up with any elegant solutions, especially for templates in public library APIs?

like image 388
Iocio Avatar asked Dec 23 '08 01:12

Iocio


2 Answers

For starters, unit test your template code with the parameter you think is most likely for a user to supply. I've often made things templates "just in case" and end up never using anything but the one type I had in mind when I wrote the original code. So in that case, testing the most likely case covers all cases!

If you feel like you need to test more, use another template argument as different as possible from the first argument. It may not be necessary to test all methods again. Some methods may not actually depend on the template parameter.

like image 197
John D. Cook Avatar answered Sep 26 '22 03:09

John D. Cook


I have an additional suggestion. In addition to unit-testing each template, examine techniques that will help constrain the potentially vast universe of template arguments that your library users might try to pass to your templates.

For example: say that you only test your templates using the type arguments "string" and "char". You do not have proof that other type arguments will be problematic for this particular template, but for one reason or another you "suspect" that other untested type args will be problematic.

In a case such as the above example, it doesn't necessarily imply that you should exhaustively test other type args. Instead, you have a case that might imply you should employ some compile-time template metaprogramming techniques to ensure that your template is never used with any other arguments but "string" and "char".

One resource:

Modern C++ Design -- by Andrei Alexandrescu

Very early on in this book, the author shows examples such as:

  • how to make a template that will self-enforce that its first type arg be of a smaller type than its second type arg

  • how to detect convertibility and inheritance at compile time

"Modern C++ Design" (despite its rather broad/vague title) is a fairly advanced exploration of template programming techniques.

like image 31
pestophagous Avatar answered Sep 25 '22 03:09

pestophagous