在C++中模仿fortran打印和编写语法
Imitating fortran print and write syntaxes in C++
我正在尝试用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}
)进行两个快速更改。
相关文章:
- 如何循环打印顶点结构
- 1d 智能指针不适用于语法 (*)++
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 助记符和指向成员语法的指针
- 有人能分解一下这个c++模板的语法吗
- C++避免重复声明的语法是什么
- QMetaObject invokeMethod的基于函数指针的语法
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- C ++有趣的语法,用于在std::cout中打印新行
- Flex Bison构造的编译器打印正确的结果,然后给出语法错误
- 没有语法错误,但没有打印结果
- c++语法,打印帮助
- 在C++中模仿fortran打印和编写语法