title: Imitating fortran print and write syntaxes in C++
body: <p>I am trying to implement a class in C++ to imitate the syntax of the print and write statements from FORTRAN. </p>
  
  <p>In order to achieve this, I implemented a class <code>fooprint</code> and overloaded <code>fooprint::operator,</code> (comma operator). Since this class should print to the standard output or to a file, I also defined two macros: <code>print</code> (for stdout) and <code>write</code> (to operate on files). </p>
  
  <p>I get compilation errors when trying to use <code>write(data) a;</code> (see below for error log). <strong>How can I get a working <code>write</code> statement with the above properties?</strong> </p>
  
  <p>This is the code (<a href="http://coliru.stacked-crooked.com/a/cfb6c1d70dfebd9a" rel="nofollow" title="C++ Web compiler at Coliru Viewer">Live Demo</a>):</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;fstream&gt;
  
  class fooprint
  {
      private:
        std::ostream *os;
  
      public:
        fooprint(std::ostream &amp;out = std::cout) : os(&amp;out) {}
        ~fooprint() { *os &lt;&lt; std::endl;}
  
        template&lt;class T&gt;
        fooprint &amp;operator, (const T output)
        {
          *os &lt;&lt; output &lt;&lt; ' ';
          return *this;
        }
  };
  
  #define print      fooprint(),     // last comma calls `fooprint::operator,`
  #define write(out) fooprint(out),
  
  int main()
  {
    double a = 2.0;
  
    print "Hello", "World!";        // OK
    print "value of a =", a;        // OK
    print a;                        // OK
  
    std::ofstream data("tmp.txt");
    write(data) "writing to tmp";   // compiles with icpc; it doesn't with g++ 
    write(data) a;                  // this won't compile
    data.close();
    return 0;
  }
  </code></pre>
  
  <p>And the compilation message:</p>
  
  <pre><code>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 a previous declaration as ‘std::ofstream data’
     error: conflicting declaration ‘fooprint a’
       write(data) a;
                   ^
     error: ‘a’ has a previous declaration as ‘double a’
  
  icpc -Wall -std=c++11 -o print print.cc
     error: "data" has already been declared in the current scope
       write(data) a;
     error: "a" has already been declared in the current scope
       write(data) a;
  </code></pre>