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

  • A+
Category:Languages

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.

 


🤔

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. Also, please don't actually define unsafe as a macro...

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: