Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Developer functions that can only be called by other developer functions

Tags:

c++

c++17

We have a number of functions that are very useful for developing and testing, but should not be part of any productive code - mostly for performance reasons. Our goal is to have the compiler ensure that functions marked as DEV_ONLY can only be called by functions with the same tag.

How would I implement something like:

virtual int foo() DEV_ONLY;

int bar() {
  foo(); // fails
}

int blah() DEV_ONLY {
  foo(); // works
}

with DEV_ONLY being a macro or something else?

The following ideas have been proposed so far, but are not completely what I am looking for:

  • volatile: One option that I found was to mark them as "volatile" (see Dr. Dobbs), but I have two issues with that. First, it would misuse a specifier that has different semantics, potentially causing issues in the future. Second, the compiler warnings about functions being "volatile" would not be as helpful.

  • friend: In my understanding, this would require friendship to be declared in the class that implements such a method. Since the tests or dev tools that use the method are not known beforehand, I am not a friend of the friend solution.

  • not exporting: The code that may or may not use the method is possibly even within the same class.

  • substituting with noop in Release build: Tests might still require those methods in Release mode.

like image 988
mrks Avatar asked Oct 28 '25 09:10

mrks


1 Answers

The #ifdef preprocessor directive should be the most straightforward way to achieve two of your goals:

  • not be part of any production code
  • ensure that they can only be called from functions with the same "tag" (if they're not there, a build with DEV_ONLY undefined would not compile)

That would mean to wrap the function bodies as well as the corresponding calls.

As to the test methods that should be available in release builds: Then they are not DEV_ONLY, and should not be marked as such.

like image 167
Cee McSharpface Avatar answered Oct 31 '25 11:10

Cee McSharpface



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!