我想创建类似于 rust 的东西 unsafe C++ 中的作用域。 我的想法是我有一些函数执行检查次数。例如:
void check() {
if (...)
throw exception(...);
}
void foo() {
check();
// do some work
}
现在,我希望能够在不执行这些检查的情况下使用或(在不同的上下文中)调用函数 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;
}
See it live on Coliru .另外,请不要实际将 unsafe
定义为宏...
关于c++ - 是否可以根据作用域改变函数的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53553675/