I am afraid that there was a misunderstanding about using static_if .
Of course, you can use static_if (or any trick you really want) to try to get some optimization, but this is not the first goal.
The first target of static_if is semantic . Let me demonstrate this with std::advance . A typical std::advance implementation will use a type switch to choose at compile time between the O (1) implementation (for random access iterators) and the O (n) implementation (for the rest):
template <typename It, typename D> void advance_impl(It& it, D d, random_access_iterator_tag) { it += d; } template <typename It, typename D> void advance_impl(It& it, D d, bidirectional_iterator_tag) { if (d > D(0)) { for (D i(0); i < d; ++i) { ++it; } } else { for (D i(0); i > d; --i) { --it; } } } template <typename It, typename D> void advance_impl(It& it, D d, input_iterator_tag) { for (D i(0); i < d; ++i) { ++it; } }
And finally:
template <typename It, typename D> void advance(It& it, D d) { typename std::iterator_traits<It>::iterator_category c; advance_impl(it, d, c); }
Why not use only if in this case? Because it will not compile.
- Bidirectional Iterator does not support
+= - The input iterator (or forward iterator) does not support
--
Thus, the only way to implement functionality is to statically dispatch functions only using the available operations for this type.
Matthieu M.
source share