Sunday, October 31, 2010

Template Specialization Warning

Say that you want to force a user to specialize a template that you have created, the following constructor would warn the user better:

   MyClass() {#error "This template needs to be specialized"}

Than

   MyClass() {This_template_needs_to_be_specialized;}

Most compilers will complain about the undefined symbol 'This_template_needs_to_be_specialized'. If you forget the ';', the compiler will focus on that error.

The #error statement is processed by the CPP (C Pre-Processor). This happens before the compiler sees any text. The preprocessor will fail the compilation in all cases when it sees this directive.

Forcing an explicit template specialization is sometimes very useful. It is analogous to a base class that has a pure virtual function, which makes the base an abstract class so that objects cannot be created from it. The abstract class specifies an interface for the derived classes to implement.

No comments:

Post a Comment