【问题标题】:Library to store an "equation" involving references?存储涉及引用的“方程式”的库?
【发布时间】:2019-04-09 03:19:01
【问题描述】:

所以我可以通过引用传递,并将该引用存储在结构或类中,如果我在其他地方进行更改并再次检查存储它的引用,更改将在那里,因为我只是访问相同的内存。

有没有图书馆可以让我做这样的事情:

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;

我可以自己制造一个,但如果有轮子,我宁愿不重新发明。

【问题讨论】:

  • 有点像......哦。您实际上是在尝试将值“绑定”到您的函数并为其创建引用。我会让一个更好的 C++ 专家回答这个问题。首先:cplusplus.com/reference/functional/bind
  • 似乎是一个解决方案,尽管结果可能看起来比我希望的更“hacky”!我什至会用 lambdas 试试看:)

标签: c++ pass-by-reference


【解决方案1】:

OP 的问题让我想起了另一个答案,我为一个带有类仿函数类的小示例编译器建模了一个 ASTThe Tiny Calculator Project

在该项目中,AST 表达式节点拥有其子(表达式)节点的所有权。

我不确定我是否正确阅读了 OP 的意图,但当然,它也可以设计为不具有子(表达式)节点所有权的表达式节点。

因此,我制作了另一个(甚至更短的)示例。此外,我重载了operator()()(而不是virtualsolve() 成员函数)。不过,在这种情况下,我认为这是一个品味问题。

示例代码:

#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

Live Demo on coliru

【讨论】:

  • 是的,这与我计划在没有现有库的情况下执行的操作类似,谢谢。
  • @Shefeto 肯定有一些库涵盖了这一点——我知道的大多数编译器都使用某种 AST。其中最流行的可能是LLVMLLVM AST。另一方面,这样的库可能非常复杂并且不太容易掌握。因此,另一种选择可能是仅根据您自己的模型完全满足您的个人需求。 (顺便说一句。图书馆的问题实际上在 SO 中是题外话。);-)
猜你喜欢
  • 2010-11-20
  • 1970-01-01
  • 2020-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 2013-05-12
  • 1970-01-01
相关资源
最近更新 更多