简体   繁体   中英

Compile-time detection of deprecated API calls?

Is there any new, cool feature in C++11 that allows us to detect at compile time whether an API now marked as deprecated is actually called by someone?

From what I've read about the new static_assert feature it doesn't seem flexible enough to be used in that kind of analysis.

But is there anything else we could use?

Optionally, is there anything in boost allowing that kind of compile-time checking?

With C++14 you will have that option :

#include <iostream>

void foo( int v ) { std::cout << v << " "; }

[[deprecated("foo with float is deprecated")]]
void foo( float v ) { std::cout << v << " "; }

[[deprecated("you should not use counter anymore")]]
int counter {};

int main() {
  foo( ++counter );
  foo( 3.14f );
}

Clang gives the compilation output ( here ) :

main.cpp:12:10: warning: 'counter' is deprecated [-Wdeprecated-declarations]
  foo( ++counter );
         ^
main.cpp:9:5: note: 'counter' has been explicitly marked deprecated here
int counter {};
    ^
main.cpp:13:3: warning: 'foo' is deprecated [-Wdeprecated-declarations]
  foo( 3.14f );
  ^
main.cpp:6:6: note: 'foo' has been explicitly marked deprecated here
void foo( float v ) { std::cout << v << " "; }
     ^
2 warnings generated.

Whether static_assert is too inflexible depends on requirements that you haven't specified, but if you want to disallow calls to deprecated APIs in your library, and those functions are templates, then it's perfect.

More likely you wish to emit some sort of mere warning when such calls are made and, to my knowledge, there is no new C++11 feature to do that.

Generally, C++ doesn't provide fine-grained control over specific compiler diagnostics/output, only "can compile" and "cannot compile" (though this is a gross over-simplification, the principle holds).

Instead, you will need to rely on compiler-specific features such as __declspec and __attribute__ .

This is not a language specific feature, it is rather compiler specific.

If an API call is marked as deprecated then your compiler should emit a warning notifying you about.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM