Last active
July 12, 2017 21:04
-
-
Save stryku/6201431b9ea4f9792c700312d55d55e7 to your computer and use it in GitHub Desktop.
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 <string> | |
#include <type_traits> | |
template <typename T> | |
std::enable_if_t<std::is_convertible_v<T, std::string>, std::string> | |
toString(const T& value) | |
{ | |
return { value }; | |
} | |
namespace details | |
{ | |
template <typename T> | |
constexpr auto canCallStdString = !std::is_same_v<T, bool> && | |
(std::is_integral_v<T> || | |
std::is_unsigned_v<T> || | |
std::is_floating_point_v<T>); | |
} | |
template <typename T> | |
std::enable_if_t<details::canCallStdString<T>, std::string> | |
toString(const T& value) | |
{ | |
return std::to_string(value); | |
} | |
std::string toString(bool b) | |
{ | |
return b ? "true" : "false"; | |
} | |
namespace details | |
{ | |
template <typename Type> | |
struct HasToString { | |
private: | |
template<typename T> | |
static constexpr auto check(T*) -> typename std::is_same< | |
decltype(std::declval<T>().toString()), | |
std::string | |
>::type; | |
template<typename> | |
static constexpr std::false_type check(...); | |
using type = decltype(check<Type>(nullptr)); | |
public: | |
static constexpr bool value = type::value; | |
}; | |
} | |
template <typename T> | |
constexpr auto HasToString = details::HasToString<T>::value; | |
template <typename T> | |
std::enable_if_t<HasToString<T>, std::string> | |
toString(const T& value) | |
{ | |
return value.toString(); | |
} | |
struct Pos | |
{ | |
int x, y; | |
std::string toString() const | |
{ | |
return "x: " + std::to_string(x) + ", y: " + std::to_string(y); | |
} | |
}; | |
template <typename ...Args> | |
void print(const Args&... args) | |
{ | |
( std::cout<< ... << (toString(args) + "\n") ); | |
} | |
int main() | |
{ | |
int foo{ -20 }; | |
double bar{ 13.22 }; | |
bool baz{ false }; | |
std::string qux{ "qux" }; | |
Pos alohomora{ 20, 40 }; | |
print(foo, bar, baz, qux, "Pos: ", alohomora); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment