Skip to content

Instantly share code, notes, and snippets.

@luluco250
Last active November 17, 2021 17:14
Show Gist options
  • Save luluco250/67a8067dd161fd8f14198e67efd5402f to your computer and use it in GitHub Desktop.
Save luluco250/67a8067dd161fd8f14198e67efd5402f to your computer and use it in GitHub Desktop.
Extension methods in C++ using desperation, sweat, tears and bubblegum
#include <iostream>
#include <string>
#include <functional>
using namespace std::placeholders;
template<typename Signature>
struct Extension {
std::function<Signature> func;
template<typename Func>
Extension(Func func) : func(func) {}
};
template<typename Signature>
void operator +(std::string& s, Extension<Signature> e) {
e.func(s);
}
constexpr char whitespace[] = " \f\n\r\t\v";
Extension<void(std::string&)> trim() {
return [](std::string& s) {
auto start = s.find_first_not_of(whitespace);
auto end = s.find_last_not_of(whitespace);
if (start != std::string::npos) s.erase(0, start);
if (end != std::string::npos) s.erase(end - start, s.size());
};
}
Extension<void(std::string&)> append(char c) {
return std::bind([](std::string& s, char c) {
s += c;
}, _1, c);
}
int main() {
std::string s = " Hello world! ";
std::cout << '"' << s << "\"\n";
s+trim();
std::cout << '"' << s << "\"\n";
s+append('x');
std::cout << '"' << s << "\"\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment