是否有可能根据范围改变功能的行为?

Igo*_*gor 6 c++ template-meta-programming c++11

我想在C++中创建类似于锈不安全范围的东西.我的想法是我有一些功能执行检查次数.例如:

void check() {
     if (...)
        throw exception(...);

}

void foo() {
     check();

     // do some work
}
Run Code Online (Sandbox Code Playgroud)

现在,我希望能够在不执行这些检查的情况下使用或(在不同的上下文中)调用函数foo().理想情况下它看起来像这样:

foo(); // call foo and perform checks
unsafe {
    foo(); // call foo without checks
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,是否有可能在编译时实现这样的东西?是否有可能以某种方式检查(或采取不同的行动)check函数的调用范围?

我只提出了一个运行时解决方案:将它包装在一些lambda中:

unsafe([&] {
    foo();
});
Run Code Online (Sandbox Code Playgroud)

不安全的地方如下:

void unsafe(std::function<void()> f)
{
     thread_local_flag = unsafe;
     f();
     thread_local_flag = safe;
}
Run Code Online (Sandbox Code Playgroud)

check()函数只检查thread_local标志,并仅在设置为时执行检查safe.

Que*_*tin 6

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;
}
Run Code Online (Sandbox Code Playgroud)

在Coliru上看到它.另外,请不要实际定义unsafe为宏...