Last active
August 29, 2015 14:04
-
-
Save dobrokot/31e4d060a3a0b7283b72 to your computer and use it in GitHub Desktop.
select different print for containers and non-containers
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
//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