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

为了实现这一点,我实现了一个fooprint类和重载的fooprint::operator,(逗号运算符)。由于此类应打印到标准输出或文件,因此,我还定义了两个宏:print(用于stdout)和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})周围进行两个快速更改。

关于c++ - 模仿C++中的fortran打印和写入语法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30949974/

10-09 22:46