在C++中模仿fortran打印和编写语法

Imitating fortran print and write syntaxes in C++

本文关键字:语法 打印 fortran C++      更新时间:2023-10-16

我正在尝试用C++实现一个类,以模仿FORTRAN中print和write语句的语法。

为了实现这一点,我实现了一个类fooprint和重载的fooprint::operator,(逗号运算符)。由于这个类应该打印到标准输出或文件,所以我还定义了两个宏:print(用于stdout)和write(用于操作文件)。

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

这是代码(实时演示):

#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})进行两个快速更改。