Last active
December 27, 2015 10:29
-
-
Save justinvh/7311553 to your computer and use it in GitHub Desktop.
type-safety through obfuscation: enforcing an output iterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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