Template Mania

WEBINAR:On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

Environment: VC6 SP5, NT4 SP3, Windows 98, Windows 2000

There is an interesting article concerning template-based technique on www.cuj.com [1]. A simple struct is introduced there that helps to implement dummy arguments converting values to distinquishable types:

template<int v>
struct Int2Type
{
enum { value = v };
};

The main article idea is generally described in terms of classes, but there is a reason why it can be especially useful for template functions with VC. There is a bug Q240871 in the Microsoft Visual C++ 6.0 compiler, its description from the MSDN is given below:

SYMPTOMS

If all the template parameters are not used in function arguments or return type of a template function, the template functions are not overloaded correctly.

CAUSE

The bug is the result of the way the compiler decorates template function names. Name Decoration uses the arguments and return type and doesn't use the explicitly specified template argument type. Therefore, all three template function instantiations receive the same decorated name<...>

RESOLUTION

Use dummy arguments to the function.

There is another interesting technique outlined in [2]. Templates do not deal with objects hierarchy, but dummy arguments combined with ellipses make it possible to specialize templates for classes and their subclasses. Let us implement a pointer validity checking utility based on these principles as an example.

MFC has two validating macros: ASSERT_VALID for CObject-based classes and ASSERT_POINTER for others. We introduce a single template function that supersedes both of them. The whole stuff being workable, some details will be omitted for simplicity. ASSERT_VALID macro invokes AfxAssertValidObject(). Among other things, it checks the object virtual table pointer. To do so, we need to find out if the class has one first. The next accessory struct can help us:

Now we can use the CHECK_ADDRESS() and CHECK_NULL_OR_ADDRESS() functions.

At the end of the article I would dare to propose an exotic way to simulate enums using templates. It was written for fun only, but seems to be interesting and can actually help when there is no other way to keep enum items together: