编译时检测不推荐的API调用?

时间:2014-02-03 11:55:01

标签: c++ boost c++11 static-assert

C ++ 11中是否有任何新的,很酷的功能允许我们在编译时检测 现在标记为已弃用的API是否实际上被某人调用了?

根据我所读到的有关新static_assert功能的内容,它似乎不够灵活,无法用于此类分析。

但我们可以使用其他任何东西吗?

可选地,是否存在允许进行这种编译时检查的任何内容?

3 个答案:

答案 0 :(得分:6)

使用C ++ 14,您将拥有该选项:

#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提供编译输出(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.

答案 1 :(得分:1)

static_assert是否过于缺乏灵活性取决于您尚未指定的要求,但如果您想禁止调用 库中已弃用的API,而那些功能都是模板,那就完美了。

在进行此类调用时,您更有可能发出某种警告,据我所知,没有新的C ++ 11功能可以执行此操作。

通常,C ++不提供对特定编译器诊断/输出的细粒度控制,只能“编译”和“无法编译”(尽管这是一个严重的过度简化,原则仍然存在)。

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

答案 2 :(得分:0)

这不是特定于语言的功能,而是特定于编译器的。

如果API调用被标记为已弃用,则编译器应发出警告通知您。