Created
November 9, 2018 22:14
-
-
Save LordAro/dff41d7da6b5c4866ccfb758348f5011 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 <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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Evil.