库存储涉及参考文献的"equation"?
Library to store an "equation" involving references?
所以我可以通过引用传递,并将该引用存储在结构或类中,如果我在其他地方进行更改并在存储它的位置再次检查该引用,更改将在那里,因为我只是访问相同的内存。
有没有一个库可以让我做这样的事情:
int foo = 9;
int bar = 5;
// obviously other arithmetic would exist too, and could be combined
Equation foo_minus_bar = Subtract(foo, bar);
// output: 4
cout << foo_minus_bar << endl;
foo = 11;
// output: 6
cout << foo_minus_bar << endl;
如果我可以访问输入(最好是平面数组或类似数组,但乞丐不能成为选择者,甚至可能是这样的东西,那就太好了:
// literal character for character output: foo - bar
cout << foo_minus_bar.formula() << endl;
我可以自己做一个,但如果轮子存在,我宁愿不重新发明轮子。
OP 的问题让我想起了另一个答案,我为一个具有类似函子类的小型示例编译器建模了一个 AST:小计算器项目。
在该项目中,AST 表达式节点拥有其子(表达式(节点的所有权。
我不确定我是否正确阅读了 OP 的意图,但当然,它也可以设计为没有子(表达式(节点所有权的表达式节点。
因此,我做了另一个(甚至更短(的例子。此外,我重载了operator()()
(而不是virtual
solve()
成员函数(。虽然,在这种情况下,我认为这是一个品味问题。
示例代码:
#include <iostream>
struct Expr {
virtual int operator()() const = 0;
};
struct ExprConst: Expr {
const int value;
ExprConst(int value): value(value) { }
virtual int operator()() const { return value; }
};
struct ExprRef: Expr {
const int &ref;
ExprRef(const int &ref): ref(ref) { }
virtual int operator()() const { return ref; }
};
struct ExprBin: Expr {
const Expr &arg1, &arg2;
ExprBin(const Expr &arg1, const Expr &arg2):
arg1(arg1), arg2(arg2)
{ }
};
struct ExprSub: ExprBin {
ExprSub(const Expr &arg1, const Expr &arg2):
ExprBin(arg1, arg2)
{ }
virtual int operator()() const { return arg1() - arg2(); }
};
int main()
{
int foo = 9;
int bar = 5;
ExprRef exprFoo(foo), exprBar(bar);
ExprSub exprSub(exprFoo, exprBar);
std::cout << "foo - bar: " << exprSub() << 'n';
std::cout << "foo = 7; bar = 10;n";
foo = 7; bar = 10;
std::cout << "foo - bar: " << exprSub() << 'n';
// done
return 0;
}
输出:
foo - bar: 4
foo = 7; bar = 10;
foo - bar: -3
科里鲁的现场演示
相关文章:
- C++错误消息*成员参考.**初学者*
- 演绎指南中的参考文献和值之间的差异
- 是指代指针正交的参考文献
- G 也抱怨不确定的参考文献,即使包括库
- 为什么认为参考文献在C 底漆第5个中没有变化,以下代码有效
- 库存储涉及参考文献的"equation"?
- 关于在ConstexPR指示和参考文献中需要固定地址的澄清
- 访问链接的列表项目从参考这些项目的参考文献中
- CXX11不确定的参考文献6.2.0
- std::tuple_size和参考文献
- 在 C++11 中使用参考文献
- 指针与参考文献
- 多态性和与参考文献的切片
- 这个临时参考文献能保存足够长的时间吗
- 关于指针和参考文献的两个简短问题
- 参考文献:我要超出范围了吗?
- COM参考文献计数问题
- 我们可以将规范性参考文献中未明确引用的内容应用到C++标准中吗
- make_pair参考文献
- 关于参考文献的问题和指向它们的指针