- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我们的 Python 代码库包含与指标相关的代码,如下所示:
class Timer:
def __enter__(self, name):
self.name = name
self.start = time.time()
def __exit__(self):
elapsed = time.time() - self.start
log.info('%s took %f seconds' % (self.name, elapsed))
...
with Timer('foo'):
do some work
with Timer('bar') as named_timer:
do some work
named_timer.some_mutative_method()
do some more work
在 Python 的术语中,计时器是一个上下文管理器。
现在我们想在 C++ 中实现相同的功能,并使用同样漂亮的语法。不幸的是,C++ 没有with
。所以“明显”的成语是(经典的 RAII)
class Timer {
Timer(std::string name) : name_(std::move(name)) {}
~Timer() { /* ... */ }
};
if (true) {
Timer t("foo");
do some work
}
if (true) {
Timer named_timer("bar");
do some work
named_timer.some_mutative_method();
do some more work
}
但这是极其丑陋的语法加盐:它比需要的多了很多行,我们不得不为我们的“未命名”计时器引入一个名称 t
(如果我们忘记了,代码会静静地中断那个名字)......它只是丑陋。
人们用来处理 C++ 中的“上下文管理器”的句法习语有哪些?
我想到了这个滥用的想法,它减少了行数但没有去掉 t
这个名字:
// give Timer an implicit always-true conversion to bool
if (auto t = Timer("foo")) {
do some work
}
或者这个建筑上的怪物,我什至不相信我自己能够正确使用它:
Timer("foo", [&](auto&) {
do some work
});
Timer("bar", [&](auto& named_timer) {
do some work
named_timer.some_mutative_method();
do some more work
});
Timer
的构造函数实际调用给定的 lambda(带有参数 *this
)并一次完成所有日志记录。
不过,这些想法似乎都不是“最佳实践”。帮帮我!
表达该问题的另一种方式可能是:如果您从头开始设计 std::lock_guard
,您将如何设计以尽可能多地消除样板代码? lock_guard
是上下文管理器的一个完美示例:它是一个实用程序,本质上是 RAII,您几乎不想为它命名。
最佳答案
可以非常接近地模仿 Python 语法和语义。以下测试用例经过编译并具有与您在 Python 中所拥有的基本相似的语义:
// https://github.com/KubaO/stackoverflown/tree/master/questions/pythonic-with-33088614
#include <cassert>
#include <cstdio>
#include <exception>
#include <iostream>
#include <optional>
#include <string>
#include <type_traits>
[...]
int main() {
// with Resource("foo"):
// print("* Doing work!\n")
with<Resource>("foo") >= [&] {
std::cout << "1. Doing work\n";
};
// with Resource("foo", True) as r:
// r.say("* Doing work too")
with<Resource>("bar", true) >= [&](auto &r) {
r.say("2. Doing work too");
};
for (bool succeed : {true, false}) {
// Shorthand for:
// try:
// with Resource("bar", succeed) as r:
// r.say("Hello")
// print("* Doing work\n")
// except:
// print("* Can't do work\n")
with<Resource>("bar", succeed) >= [&](auto &r) {
r.say("Hello");
std::cout << "3. Doing work\n";
} >= else_ >= [&] {
std::cout << "4. Can't do work\n";
};
}
}
这是给定的
class Resource {
const std::string str;
public:
const bool successful;
Resource(const Resource &) = delete;
Resource(Resource &&) = delete;
Resource(const std::string &str, bool succeed = true)
: str(str), successful(succeed) {}
void say(const std::string &s) {
std::cout << "Resource(" << str << ") says: " << s << "\n";
}
};
with
自由函数将所有工作传递给 with_impl
类:
template <typename T, typename... Ts>
with_impl<T> with(Ts &&... args) {
return with_impl<T>(std::forward<Ts>(args)...);
}
我们如何到达那里?首先,我们需要一个 context_manager
类:实现 enter
和 exit
方法的 traits 类——相当于 Python 的 __enter__
和 __exit__
。一旦 is_detected
类型特征被引入 C++,这个类也可以很容易地转发到类类型的兼容 enter
和 exit
方法T
,从而更好地模仿 Python 的语义。就目前而言,上下文管理器相当简单:
template <typename T>
class context_manager_base {
protected:
std::optional<T> context;
public:
T &get() { return context.value(); }
template <typename... Ts>
std::enable_if_t<std::is_constructible_v<T, Ts...>, bool> enter(Ts &&... args) {
context.emplace(std::forward<Ts>(args)...);
return true;
}
bool exit(std::exception_ptr) {
context.reset();
return true;
}
};
template <typename T>
class context_manager : public context_manager_base<T> {};
让我们看看这个类将如何专门用于包装 Resource
对象,或 std::FILE *
。
template <>
class context_manager<Resource> : public context_manager_base<Resource> {
public:
template <typename... Ts>
bool enter(Ts &&... args) {
context.emplace(std::forward<Ts>(args)...);
return context.value().successful;
}
};
template <>
class context_manager<std::FILE *> {
std::FILE *file;
public:
std::FILE *get() { return file; }
bool enter(const char *filename, const char *mode) {
file = std::fopen(filename, mode);
return file;
}
bool leave(std::exception_ptr) { return !file || (fclose(file) == 0); }
~context_manager() { leave({}); }
};
核心功能的实现在 with_impl
类型中。请注意套件中的异常处理(第一个 lambda)和 exit
函数如何模仿 Python 行为。
static class else_t *else_;
class pass_exceptions_t {};
template <typename T>
class with_impl {
context_manager<T> mgr;
bool ok;
enum class Stage { WITH, ELSE, DONE } stage = Stage::WITH;
std::exception_ptr exception = {};
public:
with_impl(const with_impl &) = delete;
with_impl(with_impl &&) = delete;
template <typename... Ts>
explicit with_impl(Ts &&... args) {
try {
ok = mgr.enter(std::forward<Ts>(args)...);
} catch (...) {
ok = false;
}
}
template <typename... Ts>
explicit with_impl(pass_exceptions_t, Ts &&... args) {
ok = mgr.enter(std::forward<Ts>(args)...);
}
~with_impl() {
if (!mgr.exit(exception) && exception) std::rethrow_exception(exception);
}
with_impl &operator>=(else_t *) {
assert(stage == Stage::ELSE);
return *this;
}
template <typename Fn>
std::enable_if_t<std::is_invocable_r_v<void, Fn, decltype(mgr.get())>, with_impl &>
operator>=(Fn &&fn) {
assert(stage == Stage::WITH);
if (ok) try {
std::forward<Fn>(fn)(mgr.get());
} catch (...) {
exception = std::current_exception();
}
stage = Stage::ELSE;
return *this;
}
template <typename Fn>
std::enable_if_t<std::is_invocable_r_v<bool, Fn, decltype(mgr.get())>, with_impl &>
operator>=(Fn &&fn) {
assert(stage == Stage::WITH);
if (ok) try {
ok = std::forward<Fn>(fn)(mgr.get());
} catch (...) {
exception = std::current_exception();
}
stage = Stage::ELSE;
return *this;
}
template <typename Fn>
std::enable_if_t<std::is_invocable_r_v<void, Fn>, with_impl &> operator>=(Fn &&fn) {
assert(stage != Stage::DONE);
if (stage == Stage::WITH) {
if (ok) try {
std::forward<Fn>(fn)();
} catch (...) {
exception = std::current_exception();
}
stage = Stage::ELSE;
} else {
assert(stage == Stage::ELSE);
if (!ok) std::forward<Fn>(fn)();
if (!mgr.exit(exception) && exception) std::rethrow_exception(exception);
stage = Stage::DONE;
}
return *this;
}
template <typename Fn>
std::enable_if_t<std::is_invocable_r_v<bool, Fn>, with_impl &> operator>=(Fn &&fn) {
assert(stage != Stage::DONE);
if (stage == Stage::WITH) {
if (ok) try {
ok = std::forward<Fn>(fn)();
} catch (...) {
exception = std::current_exception();
}
stage = Stage::ELSE;
} else {
assert(stage == Stage::ELSE);
if (!ok) std::forward<Fn>(fn)();
if (!mgr.exit(exception) && exception) std::rethrow_exception(exception);
stage = Stage::DONE;
}
return *this;
}
};
关于c++ - 在 C++ 中实现 "contextmanager"的最佳实践 + 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33088614/
在我的代码中,我需要能够正确打开和关闭设备,因此需要使用上下文管理器。虽然上下文管理器通常被定义为具有 __enter__ 和 __exit__ 方法的类,但似乎也有可能装饰一个函数以与上下文管理器一
这是我正在使用的代码: from contextlib import contextmanager from functools import wraps class with_report_stat
我想使用上下文管理器实现类似伪数据库的事务。 举个例子: class Transactor: def a(): pass def b(d, b): pass def c(i):
我想替换类的 __enter__/__exit__具有单个函数的函数装饰为 contextlib.contextmanager ,这里是代码: class Test: def __enter_
是否可以在上下文管理器中捕获异常? 背景:方法 get_data_from_remote_system() 每五分钟连接到远程系统并获取数据。 有时网络会关闭。 我想将异常消息抑制 30 分钟。 30
我正在尝试创建一个包装器来使上下文对象成为可选的。当条件为真时,事物应该表现得像包装的上下文对象,否则它应该表现得像无操作上下文对象。此示例适用于使用一次包装对象,但失败了,它被重新使用。 例子: i
我有以下代码 from contextlib import contextmanager @contextmanager def simple_context_manager(): print
这个问题在这里已经有了答案: "Least Astonishment" and the Mutable Default Argument (33 个答案) Python constructor an
一位同事向我指出,with 语句可能很慢。因此,我进行了测量,发现从 contextmanager 函数中获取值的时间确实比从 Python 2.7 中的生成器中获取值的时间长 20 倍,在 PyPy
为什么我可以跳过在 yield log_func 中调用 log_func,即我可以只写 yield 而代码仍然有效。这是为什么? yield 在这种情况下如何工作? import time from
假设我有一个上下文管理器: @contextmanager def cm(x): y = f(x) z = yield y g(z) 如何将 z 发送到上下文管理器? 我试过:
例如: @contextmanager def add_stuff(arg): parser = Parser(arg) # do something here yield p
我试图用上下文管理器隐藏一些 try/except 的复杂性。这是一个简单的例子: from contextlib import contextmanager import mpd mpdclient
我正在使用的库采用如下函数: @contextlib.contextmanager def stdout_cm(): yield sys.stdout 现在而不是 foo(stdout_cm)
我正在尝试在我的数据库框架中管理事务(我使用 MongoDB 和 umongo 而不是 pymongo)。 要使用事务,必须沿整个调用链传递一个session kwarg。我想提供一个上下文管理器来隔
我正在使用 SQLAlchemy 的 provided contextmanager为我处理 session 。我不明白的是如何获取自动生成的 ID,因为(1)直到调用 commit() 之后才创建
我正在尝试编写一个带有上下文管理器的多线程助手。这个想法是在一个 block 内定义一堆函数,上下文管理器“神奇地”负责调度和一切。简化的工作版本如下所示: import contextlib @co
我有以下异步函数: async def my_func(request): # preparation code here with aiohttp.ClientSession() a
我们的 Python 代码库包含与指标相关的代码,如下所示: class Timer: def __enter__(self, name): self.name = name
克隆时 Aware在我的 Android Studio 中 repo ,同步 gradle,我收到以下消息: Failed to sync Gradle project 'app' Error:Cou
我是一名优秀的程序员,十分优秀!