Check compilation time if function is used / not used C ++

I would like to check at compile time if any function of any class is used / not used, and accordingly the fail / pass compilation process.

For example, if the F1 function is called somewhere in the code, I want the compilation to succeed, and if the F2 function is called, I want it to fail.

Any ideas on how to do this using a preprocessor, templates, or any other C ++ metaprogramming method?

+6
source share
2 answers

You can achieve this with the C ++ 11 compiler if you want to change F2 to include static_assert in the function body and add a dummy template to the signature:

 #include <type_traits> void F1(int) { } template <typename T = float> void F2(int) { static_assert(std::is_integral<T>::value, "Don't call F2!"); } int main() { F1(1); F2(2); // Remove this call to compile } 

If there are no F2 subscribers, the code will compile . See this answer for why we need template cheating and it cannot just insert static_assert(false, "");

+5
source

Not a very template solution, but instead, you can rely on an outdated compiler attribute that will generate a warning if the function is used anywhere.

In the case of MSVC, you use the __declspec (deprecated) attribute:

 __declspec(deprecated("Don't use this")) void foo(); 

g ++:

 void foo() __attribute__((deprecated)); 

If you have the option “handle warnings as errors” (which you usually should), you will get the desired behavior.

 int main() { foo(); // error C4966: 'foo': Don't use this return 0; } 
+1
source

Source: https://habr.com/ru/post/953867/


All Articles