模仿C++中的fortran print and write语法

Imitating fortran print and write syntaxes in C++

我正在尝试用 C++ 实现一个 class 来模仿 FORTRAN 中打印和写入语句的语法。

为了实现这一点,我实现了一个class fooprint 并重载了fooprint::operator,(逗号运算符)。由于此 class 应打印到标准输出或文件,因此我还定义了两个宏:print(用于标准输出)和 write(用于对文件进行操作)。

我在尝试使用 write(data) a; 时遇到编译错误(请参阅下面的错误日志)。 如何获得具有上述属性的工作 write 语句?

这是代码(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 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;
}

以及编译信息:

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;

fooprint(out) 不是创建临时变量,而是声明类型为 fooprint 的变量,其名称作为宏的参数提供。为了不使它成为一个声明,而是一个表达式,您可以进行两个快速更改,将其括在括号 (fooprint(out)) 中或使用大括号初始化 (C++11) (fooprint{out}).