c++ - 如何使函数参数在 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
解决方案
当函数和调用是:
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);
}
推荐阅读
- python - Pandas:仅当某个列值在过去 N 个月内出现 N 次时才保留行
- logstash - 如何使用 - 或 _ 检查 Logstash 字段匹配的第一个字符并替换它
- json - HTTP API 调用返回 404 而 JSON 字符串返回
- flutter - 传递给另一个小部件时,Flutter formKey currentstate为null
- c++ - Winsock 有效地使用 send() 循环 (TCP)
- python - pip:约束包到最新版本
- prettier - 为 Tailwind 类禁用 prettier
- azure-devops - 在将工单添加到迭代之前,有关工作项的必需信息
- lisp - Lisp 中的反引号扩展
- android - 如何从 android 控制台中完全删除应用程序?