首页 > 解决方案 > 如何使函数参数在 C++ 中以单行方式传递之前和之后执行某些操作

问题描述

我想让一个对象在作为参数传递给函数之前和之后做一些事情,但是(1)不修改函数和(2)以一种简洁的方式。

这是我想到的第一个,RAII。但是,我认为表达方式(x.lock(), x)很丑陋。

我认为肯定会有一个很好的解决方案,但我想不出一个。

#include <iostream>
using namespace std;

// I can change this class
struct RAII {
  RAII() {
    cout << "do sth globally" << endl;
  }
  ~RAII() {
    cout << "revert it" << endl;
  }
};

class A {
  public:
    // I can change this function, too.
    auto lock() {
      return RAII();
    }
};

void f(const A& obj) {
  cout << "a function that I can't change" << endl;
}

int main() {
  A x;
 // I think the expression is somewhat ugly.
 // Can I make this a more neat one-liner, like f(x.locked())?
  f((x.lock(), x));
}

输出与下面相同。

do sth globally
a function that I can't change
revert it

标签: c++

解决方案


当函数和调用是:

void f(const A& obj);
f(x);

你不能改变这些。没有办法让对象知道正在使用的引用。

但是,您可以调用不同的函数:

void f2(const A& obj) {
     obj.before();
     f(obj);
     obj.after();
}

f2(x); // <- one line

有了 RAII,这将是类似的东西

struct helper {
      const A& obj;
      helper(const A& obj) : obj(obj) { before(obj); }
      ~helper() { after(obj); }
};

void f2(const A& a) {
    helper h{a};
    f(a);
}

推荐阅读