gpt4 book ai didi

c++ - 在 C++ 中实现 "contextmanager"的最佳实践 + 语法

转载 作者:可可西里 更新时间:2023-11-01 16:38:42 25 4
gpt4 key购买 nike

我们的 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 类:实现 enterexit 方法的 traits 类——相当于 Python 的 __enter____exit__。一旦 is_detected 类型特征被引入 C++,这个类也可以很容易地转发到类类型的兼容 enterexit 方法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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com