fstream - Imitating fortran print and write syntaxes in C++ -
i trying implement class in c++ imitate syntax of print , write statements fortran.
in order achieve this, implemented class fooprint
, overloaded fooprint::operator,
(comma operator). since class should print standard output or file, defined 2 macros: print
(for stdout) , write
(to operate on files).
i compilation errors when trying use write(data) a;
(see below error log). how can working write
statement above properties?
this code (live demo):
#include <iostream> #include <fstream> class fooprint { private: std::ostream *os; public: fooprint(std::ostream &out = std::cout) : os(&out) {} ~fooprint() { *os << std::endl;} template<class t> fooprint &operator, (const t output) { *os << output << ' '; return *this; } }; #define print fooprint(), // last comma calls `fooprint::operator,` #define write(out) fooprint(out), int main() { double = 2.0; print "hello", "world!"; // ok print "value of =", a; // ok print a; // ok std::ofstream data("tmp.txt"); write(data) "writing tmp"; // compiles icpc; doesn't g++ write(data) a; // won't compile data.close(); return 0; }
and compilation message:
g++ -wall -std=c++11 -o print print.cc error: conflicting declaration ‘fooprint data’ #define write(out) fooprint(out), ^ note: in expansion of macro ‘write’ write(data) a; ^ error: ‘data’ has previous declaration ‘std::ofstream data’ error: conflicting declaration ‘fooprint a’ write(data) a; ^ error: ‘a’ has previous declaration ‘double a’ icpc -wall -std=c++11 -o print print.cc error: "data" has been declared in current scope write(data) a; error: "a" has been declared in current scope write(data) a;
fooprint(out)
not creation of temporary rather declaration of variable of type fooprint
name provided argument macro. in order not make declaration, , instead expression, 2 quick changes can make surrounding in parenthesis (fooprint(out))
or using brace-initialization (c++11) (fooprint{out}
).
Comments
Post a Comment