Monday, 16 April 2012

Unit Testing when the success case is compilation failure (with C++)

There is an issue with the use of Window’s COM types being used with STL containers in versions of Visual Studio prior to 2010. The crux of the matter is that various COM types define the address-of operator and instead of returning the real address of the object they return a logical address. If the STL container re-arranges its contents this can lead to corruption as it can unwittingly manipulate an object at the incorrect address.

The prescribed solution to this problem is to not place the COM types directly into the STL container but instead wrap them with the ATL CAdapt class.  When adopting this approach there are two important aspects to consider:

  • Firstly, is there a way to prevent incorrect usage of the containers?
  • Secondly, assuming this is possible, is there a way to make sure it covers the various permutations of STL containers and COM types that are being used?

It turns out that the first issue is easily solved using template specialization.  The hard part though is creating  a set of unit tests that ensure specializations have been created for all permutations and that they are active.  This is made even more difficult by the fact a successful use of the specialization results in compilation failure.

This too can be solved by combing various template mechanisms and techniques: SFINAE & Template Meta-programming etc.  In the April issue of the ACCU Overload journal I have written article that describes this problem along with the solution.  Please follow the link below (and then jump to page 24 in the PDF if it doesn't open there automatically).

The complete source code the article is also available on GitHut:


Martin Moene said...

You can use a URL as the following to directly jump to the desired page:


Pete Barber said...

Thanks for the tip Martin. Post updated.

Anonymous said...

Interesting technique and a very good article.