Mandatory template arguments

Consider the following function declaration:

template <typename ... Items_To_Print>
void print_as_csv(std::ostream & stream, char delimiter, Items_To_Print && ... items_to_print);

Though the declaration may seem rather involved, the actual application of this function is quite simple:

print_as_csv(std::cout, ';', 2.0, 42, "hello");

The compiler knows how to create an instance of print_as_csv by a mechanism called template argument deduction. It works only for functions, because the compiler needs arguments to deduce the types from. There are, however, template functions for which not all template arguments can be deduced by the compiler.

Continue reading “Mandatory template arguments”

Mopping up template barf with static_assert

Templates are a mixed blessing for C++ developers. On the one hand, templates avoid code duplication as most impressively demonstrated by the standard template library. The template mechanism, in contrast to preprocessor macros, is aware of the C++ language and part of it. Compilers can produce helpful error messages – and some compilers even do so.

Some compilers, however, fail in providing clear template compilation error messages. If you make a mistake, you are greeted by a bucket load of irritating notes on what went wrong in detail. Since it is down to you to identify the relevant chunks, this is often referred to as template barf.

Continue reading “Mopping up template barf with static_assert”