Skip to content

Instantly share code, notes, and snippets.

@dobrokot
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dobrokot/31e4d060a3a0b7283b72 to your computer and use it in GitHub Desktop.
Save dobrokot/31e4d060a3a0b7283b72 to your computer and use it in GitHub Desktop.
select different print for containers and non-containers
//compile with g++ -std=c++11 select_print.cpp
#include <vector>
#include <iostream>
#include <string>
namespace detail {
struct FromAny {
template <class T> FromAny(const T&) {}
};
struct Printer1 {
template <class T> void PrintImpl(const T& x) {
std::cout << x << '\n';
}
};
struct Printer2 {
template <class T> void PrintImpl(const T& x) {
for (auto &y: x)
std::cout << y << "; ";
std::cout << '\n';
}
};
Printer1 SelectPrinter(FromAny) { return Printer1(); }
template <class T>
Printer2 SelectPrinter(const T &x, typename T::iterator *_not_used = (sizeof(T().begin()), nullptr) ) {
return Printer2();
}
}
template <class T> void Print(const T&x) {
detail::SelectPrinter(x).PrintImpl(x);
}
int main() {
std::vector<int> v = {0, 1, 2};
int i = 33;
Print(i);
Print(v);
Print("hello");
Print(std::string("hello"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment