Skip to content

Instantly share code, notes, and snippets.

@justinvh
Last active December 27, 2015 10:29
Show Gist options
  • Save justinvh/7311553 to your computer and use it in GitHub Desktop.
Save justinvh/7311553 to your computer and use it in GitHub Desktop.
type-safety through obfuscation: enforcing an output iterator
#include <iterator>
#include <type_traits>
#include <iostream>
template <class Iter, class Tag>
using has_tag =
std::enable_if<
std::is_convertible<
typename std::iterator_traits<Iter>::iterator_category,
Tag>::value,
Iter>;
template <typename Iter>
using is_output_iterator = has_tag<Iter, std::output_iterator_tag>;
template<class Iter, class Value = typename Iter::value_type,
class = typename is_output_iterator<Iter>::type>
void do_something(std::initializer_list<Value> xs, Iter& iter)
{
for (const Value& x : xs) {
*iter = x;
++iter;
}
}
int main()
{
// fails as expected
// auto iiter = std::istream_iterator<int>();
// do_something({1, 2, 3, 4}, iter);
// passes
auto oiter = std::ostream_iterator<int>(std::cout, " ");
do_something({1, 2, 3, 4}, oiter);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment