Skip to content

Instantly share code, notes, and snippets.

@stryku
Last active July 12, 2017 21: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 stryku/6201431b9ea4f9792c700312d55d55e7 to your computer and use it in GitHub Desktop.
Save stryku/6201431b9ea4f9792c700312d55d55e7 to your computer and use it in GitHub Desktop.
#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