Compile time check if a function is used/unused c+

2019-04-08 10:46发布

问题:

I'd like to check during compile time if some function of some class is used/not used, and accordingly fail/pass the compilation process.

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

Any ideas on how to do that, with usage of preprocessor, templates or any other c++ metaprogramming technique?

回答1:

You can achieve this with a c++11 compiler provided you are willing to modify F2 to include a 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 callers of F2, the code will compile. See this answer for why we need the template trickery and can't simply insert a static_assert(false, "");



回答2:

Not a very templatey solution, but instead you can rely on compiler's deprecated attribute that will generate warning if a function is used anywhere.

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

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

G++:

void foo() __attribute__((deprecated));

If you have "treat warnings as errors" compile option on (which you generally should) you'll get your desired behaviour.

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