Maintainability of templates is a problem. This is a simple fact, when you're working outside the community dedicated to generic libraries. I don't want my friends and colleagues to have to use Clang to run my code, simply because... well... then it's not really generic and portable, is it? But I do desperately want to be able to write some templated code now and then.
What are some tricks you use to make templated code more usable, more maintainable, and just outright more readable? Things like descriptive template arguments, enable-ifs, and similar little quirks of code style, all the way up to advice regarding things like which compilers support variadic templates or what template (anti-)patterns to avoid.
In short, what idioms should I avoid? Which should I lean on?
I want my code to be elegant but not too elegant.
Some resources I have found:
C++ FAQ
Error Decrypt
What are variadic templates?
I use the following approach:
detail_
namespace; only expose what is necessary.iterator_transformer<Iter, F>
is constructed by transform_iterator
._traits
, _concept
, ...) and stick to it (1)type
is the "return type" of a metafunction which returns types, value
is the static const return type of a function returning a static const integer, other
is for metafunctions returning templates. You may want to use boost MPL if you abuse metaprogramming, and follow their conventions (thanks @Noah Roberts)enable_if
, it makes the code less readable. You can use it internally however.enable_if
. Keep it simple.(1) I use _concept
for base classes for the CRTP pattern (ie. "static polymorphism"). CRTP is good as it allows you to refine a default implementation with minimal code.
I agree with most answers here which state that templates are an (increasingly ?) important component of the language, and that no one can pretend being a C++ developer without an ability to read some reasonable template code.
However, templates can get messy, so I tend to follow a few guidelines :
details
namespace or, even better, in a separated header filetypedef
as much as possible : when a 'family' of template classes work together and tend to expect the very same template arguments, provide nested typedef (either in the 'main' library object, or in a separate template struct
).I don't really understand. The problems with templates are due to the difficulty of getting the include orders and declaration/definition orders correct, not portability.
Templated code is no less portable than regular code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With