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

旧城冷巷雨未停 提交于 2019-12-06 03:57:09

问题


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;
}


来源:https://stackoverflow.com/questions/18813731/compile-time-check-if-a-function-is-used-unused-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!