vendredi 30 novembre 2018

Is it possible to change behavior of function based on scope?

I would like to create something similar to rust unsafe scope in C++. The idea is that I have some functions performing number of checks. For example:

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

}

void foo() {
     check();

     // do some work
}

Now, I want to be able to call function foo() with or (in different context) without performing those checks. Ideally it would look like this:

foo(); // call foo and perform checks
unsafe {
    foo(); // call foo without checks
}

My question is, is it possible to achieve something like this in compile time? Is it possible to somehow check (or act differently) from check function in what scope it is called?

I came up only with a runtime solution: to wrap it in some lambda:

unsafe([&] {
    foo();
});

where unsafe is implemented as follows:

void unsafe(std::function<void()> f)
{
     thread_local_flag = unsafe;
     f();
     thread_local_flag = safe;
}

check() function would just check for the thread_local flag and perform checks only when it is set to safe.

Aucun commentaire:

Enregistrer un commentaire