c++ - 是否可以根据作用域改变函数的行为?

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

我想创建类似于 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/

相关文章:

C++ IO 二进制文件流 : default value when output isn't specified

c++ - 构造 std::tuple 类型的索引数组

c++ - 引用模板元编程

c++ - range-for 表达式中的临时生命周期

c++ - 没有用于使用可变参数调用 std::forward(const std::string &) 的匹配函数

c++ - C++ 中的无锁数据结构 = 仅使用原子和内存排序?

C++ 可变参数模板类终止

c++ - 内存与无理数与 float

c++ - 无法从 C++ 中的函数捕获异常

c++ - 运算符 x++;和++x;对于 int。哪个更快?为什么?