编译时检查函数是否使用/未使用 c++
Compile time check if a function is used/unused c++
我想在编译时检查是否使用/不使用某个类的某些函数,并相应地失败/通过编译过程。
例如,如果在代码中的某处调用函数F1
,我希望编译成功,如果调用函数F2
,我希望它失败。
关于如何使用预处理器、模板或任何其他 C++ 元编程技术来做到这一点的任何想法?
您可以使用
c++11 编译器实现此目的,前提是您愿意修改 F2 以在函数体中包含static_assert并向签名添加虚拟模板:
#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
}
如果没有 F2 的调用方,代码将编译。请参阅此答案,了解为什么我们需要模板技巧并且不能简单地插入static_assert(false, "");
不是一个非常模板化的解决方案,但相反,您可以依赖编译器的已弃用属性,如果函数在任何地方使用,该属性将生成警告。
对于 MSVC,请使用 __declspec(已弃用)属性:
__declspec(deprecated("Don't use this")) void foo();
G++:
void foo() __attribute__((deprecated));
如果您有"将警告视为错误"编译选项(您通常应该这样做),您将获得所需的行为。
int main()
{
foo(); // error C4966: 'foo': Don't use this
return 0;
}
相关文章:
- 普通环路未使用gcc 4.8.5自动矢量化
- 在更改for循环的第三部分后,未使用for循环结果
- 使用typeid警告未使用的变量
- C++删除未使用的类属性会导致 std::logic_error
- 警告 C4552:">>":未使用表达式的结果
- (SFML)按下键时,播放器构造函数未使用正确的动画进行更新
- 为什么我会收到警告,指出函数已使用但未定义,以及已定义但未使用?
- 如果我想链接静态库并删除未使用的符号.txt我应该如何处理 Cmakelist
- 可视化C++载体:未使用的容量
- GCC 中 __attribute__((未使用)) 和 __attribute((未使用)) 之间的区别
- 循环访问还包含未使用元素的字符串数组
- Q维德格特关闭事件(..)未使用 QProcess::terminate() 调用
- Visual Studio "fatal error LNK1104: cannot open file"未使用或包含的库
- G++ 编译器是否在未使用返回值的情况下将 constexpr 函数视为常规函数?
- 链接器输入文件未使用,因为链接未完成,我无法获得.o
- 未使用的C++未优化的静态成员函数/变量
- 仅当一个参数中未使用 std::function 时,模板函数替换才有效
- 如何控制或优化或删除或释放 UNION 中未使用的内存
- 未使用的 asm() 在不受支持的体系结构上的行为
- isPalindrome不显示输出,isPalindrome函数未使用字符串输入作为字符串参数进行测试