Skip to content

Instantly share code, notes, and snippets.

@LordAro
Created November 9, 2018 22:14
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 LordAro/dff41d7da6b5c4866ccfb758348f5011 to your computer and use it in GitHub Desktop.
Save LordAro/dff41d7da6b5c4866ccfb758348f5011 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <type_traits>
#include <vector>
template<typename, typename = void>
struct is_std_container : std::false_type {};
template<typename T>
struct is_std_container<T,
std::void_t<decltype(std::declval<T&>().begin()),
decltype(std::declval<T&>().end()),
typename T::value_type
>>
: std::true_type {};
// std::negation in C++17
template<class B>
struct negation : std::integral_constant<bool, !bool(B::value)> { };
// Things that can use std::to_string, in general
template<typename T>
inline typename std::enable_if_t<std::is_arithmetic<T>::value, std::string>
to_s(T arg)
{
return std::to_string(arg);
}
// Base case
template<typename T>
inline typename std::enable_if_t<std::is_convertible<T, std::string>::value, std::string>
to_s(T arg)
{
return arg;
}
// Containers (but not strings, otherwise ambiguity
template<typename T>
typename std::enable_if_t<is_std_container<T>::value
&& negation<std::is_convertible<T, std::string>>::value, std::string>
to_s(T c, const std::string &sep=", ")
{
std::string s = "{" + to_s(*c.begin());
for (auto &&it = c.begin() + 1; it < c.end(); ++it) {
s += sep + to_s(*it);
}
return s + "}";
}
// Base case, trailing newline
template<typename T = void>
std::string concat()
{
return "\n";
}
template<typename T, typename ...Ts>
std::string concat(T arg, Ts... args)
{
return to_s(arg) + concat(args...);
}
int main()
{
std::vector<int> v = {0, 1, 42};
std::vector<std::vector<std::string>> v2 {{"a", "#w3"}, {"asd", "sdfg", "po"}};
std::cout << concat("Hello there, I am ", 23, " years old and I have this vector: ", v);
std::cout << concat("I also have this strange vector: ", v2);
}
@sdhand
Copy link

sdhand commented Nov 9, 2018

Evil.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment