c++ - 是否可以根据范围改变函数的行为?
问题描述
我想在 C++中创建类似于 rust unsafe范围的东西。这个想法是我有一些功能执行检查次数。例如:
void check() {
if (...)
throw exception(...);
}
void foo() {
check();
// do some work
}
现在,我希望能够在不执行这些检查的情况下使用 or (在不同的上下文中)调用函数 foo()。理想情况下,它看起来像这样:
foo(); // call foo and perform checks
unsafe {
foo(); // call foo without checks
}
我的问题是,是否有可能在编译时实现这样的目标?是否有可能以某种方式从check
函数中检查(或采取不同的行动)它被调用的范围?
我只提出了一个运行时解决方案:将其包装在一些 lambda 中:
unsafe([&] {
foo();
});
其中 unsafe 的实现方式如下:
void unsafe(std::function<void()> f)
{
thread_local_flag = unsafe;
f();
thread_local_flag = safe;
}
check() 函数只会检查 thread_local 标志并仅在它设置为时执行检查safe
。
解决方案
namespace detail_unsafe {
thread_local int current_depth;
struct unsafe_guard {
unsafe_guard() { ++current_depth; }
~unsafe_guard() { --current_depth; }
unsafe_guard(unsafe_guard const &) = delete;
unsafe_guard &operator = (unsafe_guard const &) = delete;
};
}
#define unsafe \
if(::detail_unsafe::unsafe_guard _ug; false) {} else
bool currently_unsafe() {
return detail_unsafe::current_depth > 0;
}
在 Coliru 上现场观看。另外,请不要真正定义unsafe
为宏...
推荐阅读
- elixir - 插入 utc_datetime 值时混合测试中的 CaseClauseError
- pyspark - Pyspark:在groupBy之后删除列条件上的行
- c# - Windows ui 自动化和远程桌面连接问题
- angular - 如何运行角度应用程序?
- javascript - 将网站操作链接添加到 android 本机共享小部件?
- ios - IOS企业自发行不可下载
- ios - 我可以在 ios swift 内置方法(如 print())上添加警告或错误消息,以便如果有人使用该方法,他们可以发出警告消息吗?
- java - Zookeeper 不适用于安装在 32 位 Windows 上的 JRE
- java - “pl00092”:空值:IDP 没有回复断言
- tortoisegit - 如何使用 TortoiseGit 执行 git 命令 `git reset --hard origin/master`?