Section 8.5.  Details
Team LiB
Previous Section Next Section

8.5. Details

Instantiation backtraces

Those long error messages you get when templates fail to compile are actually the compile time equivalent of the runtime call stack: They often contain valuable information that can help lead you to the source of a problem, if you can manage not to be overwhelmed by them. Compiler vendors have taken a number of steps, including the use of "with" clauses and eliminating default template parameters, to make them more readable.

typedef substitution

Many compilers, including Microsoft Visual C++ 7 and 7.1 and most EDG-based compilers, attempt to improve error messages by presenting types the way they were originally named in code. For example, they may show a typedef name instead of presenting the underlying type referred to by that typedef. We feel that substitution of class-template scoped typedefs actually hurts metaprogram debugging more than it helps, since metafunction results are always accessed through nested typedefs. We suggest you keep at least one compiler handy that doesn't do deep typedef substitution. GCC is one such a compiler, and it's free.

Additional tools

Because instantiation backtraces report errors at many lines of a program, we suggest you get an IDE of some kind that automatically displays the program text associated with line numbers in error messages, so you can quickly inspect the code at each level of an instantiation stack backtrace. We also suggest you try using a post-processing filter such as STLFilt to improve the readability of your template error messages.

Static assertions

BOOST_STATIC_ASSERT, BOOST_MPL_ASSERT_RELATION, and straightforward uses of BOOST_MPL_ASSERT are great tools for adding sanity checks to your metaprograms. They're also useful for writing metaprogram tests that are expected to compile only if the code is correct. For enforcing constraints on the way your metaprograms are used, we suggest something that produces more readable error messages.

Customized errors

We only know of one reasonably portable way to generate a specific message when a template is instantiated: embed it in the name of a type or function that will show up in a real compiler diagnostic. We covered two approaches: BOOST_MPL_ASSERT with hand written predicate metafunctions and BOOST_MPL_ASSERT_MSG. Each has its strengths and weaknesses. Though workable, neither is really a clean solution. In the future, we hope direct language support for custom diagnostics will be available.

Type printing

The "customized error message" technique can be extended to warnings if you need to examine a type without disturbing metaprogram execution. The mpl::print<T> class template can be used to generate such a warning on a wide variety of compilers, depending on your choice of compilation options.

    Team LiB
    Previous Section Next Section