首页 > 解决方案 > 是否可以根据范围改变函数的行为?

问题描述

我想在 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

标签: c++c++11template-meta-programming

解决方案


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为宏...


推荐阅读