for (TContainer::const_iterator it = coll.begin(), end = coll.end(); it != end; ++it)again and again. Since C++11, we have range-based loop, something that Perl, JavaScript and BASH already have years ago.
Speaking of Perl, today I found out how easy it is to implement a Perl-like
join
. Below is an example.#include <cstdio> #include <string> #include <sstream> class join { public: join(char ch) : m_sDelimiter(1u, ch) {} join(const char * sz) : m_sDelimiter(sz) {} template <typename T> std::string operator()(T && arg) { std::stringstream ss; ss << arg; return ss.str(); } template <typename T0, typename... argTs> std::string operator()(T0 && arg0, argTs&&... args) { std::stringstream ss; ss << arg0 << m_sDelimiter << (*this)(args...); return ss.str(); } private: std::string m_sDelimiter; }; int main(int argc, char * argv[]) { std::string && s = join(", ")("apple", 135, "banana", 2.46, "cherry"); ::printf("%s\n", s.c_str()); return 0; }Yes, I knew there were
boost::join
already, but boost::join
doesn't allow us to join elements of different data types, which sometimes is not as convenient as Perl's built-in function join
.
No comments:
Post a Comment