C++でPerlのvoid contextを再現する
dump(1); string s = dump(2);
と書いたときの動作を変える。
#include <iostream> #include <sstream> #include <string> using namespace std; template<typename T> class dump_context { private: const T& v; bool flag; public: dump_context(const T& v) : v(v), flag(true) {} ~dump_context() { if(flag) { // void context cout << v << endl; } } operator const string&() { flag = false; ostringstream os; os << v; return os.str(); } }; template<typename T> dump_context<T> dump(const T& v) { return dump_context<T>(v); } int main(int argc, char **argv) { dump(1); string s = dump(2); return 0; }