Last active
August 29, 2015 14:09
-
-
Save dannvix/2bf08c3be5bd94cf7410 to your computer and use it in GitHub Desktop.
Playing with C++11 type traits and templates
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 <iostream> | |
#include <iterator> | |
#include <vector> | |
#include <set> | |
// overload for all STL containers | |
template < | |
typename T, | |
typename = typename std::enable_if < | |
std::is_convertible< | |
typename std::iterator_traits< | |
typename T::iterator | |
>::iterator_category, | |
std::input_iterator_tag | |
>::value, bool | |
>::type | |
> | |
std::ostream& operator<< (std::ostream &s, const T& ref) { | |
s << "(generic) ["; | |
for (auto it = ref.begin(); it != ref.end(); it++) { | |
s << (it != ref.begin() ? ", " : "") << *it; | |
} | |
return s << "]"; | |
} | |
// vector-only, with type traits | |
// template < | |
// typename Y, | |
// typename std::enable_if< | |
// std::is_convertible< | |
// Y, | |
// std::vector< | |
// typename std::iterator_traits< | |
// typename Y::iterator | |
// >::value_type | |
// > | |
// >::value, bool | |
// >::type | |
// > | |
// std::ostream& operator<< (std::ostream &s, const Y& ref) { | |
// s << "(vector) ["; | |
// for (auto it = ref.begin(); it != ref.end(); it++) { | |
// s << (it != ref.begin() ? ", " : "") << *it; | |
// } | |
// return s << "]"; | |
// } | |
// vector-only | |
template <typename T> | |
std::ostream& operator<< (std::ostream &s, const std::vector<T>& v) { | |
s << "(vector) ["; | |
for (auto it = v.begin(); it != v.end(); it++) { | |
s << (it != v.begin() ? ", " : "") << *it; | |
} | |
return s << "]"; | |
} | |
int main (void) { | |
std::vector<double> v{1.1, 2.2, 3.3}; | |
std::set<int> s{1, 2, 3}; | |
std::vector<std::set<int>> vs{s, {5, 6, 7}, s}; | |
std::cout << v << std::endl; | |
std::cout << s << std::endl; | |
std::cout << vs << std::endl; | |
// (vector) [1.1, 2.2, 3.3] | |
// (generic) [1, 2, 3] | |
// (vector) [(generic) [1, 2, 3], (generic) [5, 6, 7], (generic) [1, 2, 3]] | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment