gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:41:56 26 4
gpt4 key购买 nike

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

为了实现这一点,我实现了一个类 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 print and write语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30949974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com